The only tool you need to know what is happening and how to fix it.
Go alertingexception-trackerissue-trackinglogsmetricsmonitoringobservability-platformopen-telemetryotelsession-replaytelemetrytraces
feat: add DuckDB telemetry backend for self-hosted mode (#203) (#254)
Jovan Stojiljkovic4e6dda3a7ff3
diff --git a/.github/workflows/benchmark-hardware.yml b/.github/workflows/benchmark-hardware.ymlindex e7ac02d0..3d36801e 100644--- a/.github/workflows/benchmark-hardware.yml+++ b/.github/workflows/benchmark-hardware.yml@@ -10,7 +10,7 @@ on:required: truedefault: 'ccx13,ccx23,ccx33'modes:- description: 'Comma-separated DB modes (sqlite,pgch,managed-ch). managed-ch points at an external ClickHouse and requires the BENCH_CH_* repository secrets.'+ description: 'Comma-separated DB modes (sqlite,duckdb,pgch,managed-ch). duckdb is the self-hosted DuckDB telemetry backend (SQLite main + DuckDB telemetry). managed-ch points at an external ClickHouse and requires the BENCH_CH_* repository secrets.'required: truedefault: 'sqlite,pgch'signals:@@ -50,13 +50,22 @@ on:description: 'Read-probe fill phase request rate override (default 100 req/s). Combined with fill_batch_size sets total ingest rate. Lower together for SQLite to keep step-target overshoot small. Ignored unless scenario=read-probe.'required: falsedefault: ''+ fill_levels:+ description: 'Read-probe fill ladder override, comma-separated row counts (default 100000,1000000,10000000,100000000). e.g. 10000000,100000000,1000000000 to probe 1B — raise duration to cover the fill, it is a hard cap on the whole run. Ignored unless scenario=read-probe.'+ required: false+ default: ''+ commit_results:+ description: 'Commit results to the dispatched ref (REPLACES the whole scenario results folder with only this dispatch''s entries). Set false for exploratory or partial-matrix runs — per-entry result JSONs are still available as the matrix jobs'' workflow artifacts.'+ required: true+ type: boolean+ default: trueconcurrency:group: benchmark-hardwarecancel-in-progress: falsepermissions:- contents: write # aggregate job commits the results back to main+ contents: write # aggregate job commits the results back to the dispatched refjobs:setup:@@ -103,6 +112,7 @@ jobs:LOADGEN_TIER: ${{ github.event.inputs.loadgen_tier }}BENCH_FILL_BATCH_SIZE: ${{ github.event.inputs.fill_batch_size }}BENCH_FILL_REQUEST_RATE: ${{ github.event.inputs.fill_request_rate }}+ BENCH_FILL_LEVELS: ${{ github.event.inputs.fill_levels }}# Managed-ClickHouse credentials. Used only when modes contains# managed-ch; empty for sqlite/pgch entries (harmless — sut-bootstrap# only validates them when MODE=managed-ch).@@ -187,12 +197,28 @@ jobs:echo "dst=${dst}" >> "$GITHUB_OUTPUT"ls -la "${dst}"+ # Committing replaces the scenario folder wholesale, so a dispatch+ # where some matrix entries failed (quota, OOM, flake) would push a+ # PARTIAL result set, silently deleting the published JSONs for the+ # missing entries. Fail instead: the per-entry artifacts are already+ # uploaded, and a clean re-dispatch is cheap.+ count_csv() { tr ',' '\n' <<<"$1" | sed 's/ //g' | grep -c . ; }+ expected=$(( $(count_csv "${{ github.event.inputs.tiers }}") \+ * $(count_csv "${{ github.event.inputs.modes }}") \+ * $(count_csv "${{ github.event.inputs.signals }}") ))+ staged=$(find "${dst}" -name '*.json' | wc -l | tr -d ' ')+ if [[ "${staged}" -lt "${expected}" ]]; then+ echo "only ${staged}/${expected} matrix entries produced results — refusing to commit a partial set" >&2+ exit 1+ fi+- name: Render chartsrun: |pip install --quiet matplotlibpython3 benchmarks/scripts/chart.py "${{ steps.stage.outputs.dst }}"- name: Commit results+ if: ${{ github.event.inputs.commit_results == 'true' }}run: |set -euo pipefailgit config user.name "traceway-bot"@@ -207,9 +233,12 @@ jobs:tmp_staged="$(mktemp -d)/staged"cp -a "${staged}" "${tmp_staged}"- echo "syncing checkout to latest origin/main before committing"- git fetch origin main- git reset --hard origin/main+ # Sync to the DISPATCHED ref, not main — a branch dispatch that+ # resets to origin/main commits main+1 onto the branch and the+ # push is rejected as non-fast-forward.+ echo "syncing checkout to latest origin/${GITHUB_REF_NAME} before committing"+ git fetch origin "${GITHUB_REF_NAME}"+ git reset --hard "origin/${GITHUB_REF_NAME}"# Wipe whatever main had at this scenario folder (probably a prior# dispatch of the SAME scenario) and replace it with this@@ -230,5 +259,5 @@ jobs:exit 0figit commit -m "bench: ${{ github.event.inputs.scenario }} $(date -u +%Y-%m-%d)"- git pull --rebase origin main+ git pull --rebase origin "${GITHUB_REF_NAME}"git pushdiff --git a/CLAUDE.md b/CLAUDE.mdindex 0e1f8366..5f08fefc 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -86,7 +86,7 @@ All PostgreSQL operations should use `ExecuteTransaction` for automatic commit/rproject, err := pgdb.ExecuteTransaction(func(tx *sql.Tx) (*models.Project, error) {// All repository calls receive the transaction- return repositories.ProjectRepository.FindById(tx, id)+ return transactional.ProjectRepository.FindById(tx, id)})```@@ -103,7 +103,7 @@ func (c *AuthController) Register(ctx *gin.Context) {tx := middleware.GetTx(ctx) // Get transaction from context// Use tx for all repository calls- user, err := repositories.UserRepository.FindByEmail(tx, email)+ user, err := transactional.UserRepository.FindByEmail(tx, email)if err != nil {ctx.JSON(500, gin.H{"error": err.Error()})return // Transaction auto-rolls back on non-success status@@ -201,7 +201,7 @@ func (r *userRepository) CountByOrganization(tx *sql.Tx, orgID uuid.UUID) (int,```go// CORRECT - check for nil-user, err := repositories.UserRepository.FindByEmail(tx, email)+user, err := transactional.UserRepository.FindByEmail(tx, email)if err != nil {return nil, err // actual database error}@@ -211,7 +211,7 @@ if user == nil {}// WRONG - do not use sql.ErrNoRows with lit-user, err := repositories.UserRepository.FindByEmail(tx, email)+user, err := transactional.UserRepository.FindByEmail(tx, email)if err == sql.ErrNoRows { // This won't work with lit!// ...}@@ -252,6 +252,11 @@ POSTGRES_USERNAME=tracewayPOSTGRES_PASSWORD=POSTGRES_SSLMODE=disable+# DuckDB telemetry backend (only with -tags telemetry_duckdb build; see "DuckDB Telemetry Backend" below)+DUCKDB_MEMORY_LIMIT= # e.g. 4GB. Unset = DuckDB auto-tunes (~80% RAM). Set explicitly in memory-capped containers to avoid OOM.+DUCKDB_THREADS= # e.g. 4. Unset = DuckDB auto-tunes (= cores). Cap in constrained/shared environments.+DUCKDB_CHECKPOINT_THRESHOLD= # e.g. 256MB. Unset = DuckDB default (16MB). Raise under sustained ingest to reduce WAL checkpoint stalls; costs a larger WAL and longer restart replay.+# NotificationsNOTIFICATION_POLL_SECONDS=60 # polled rule evaluation interval; minimum 5, invalid values fall back to 60@@ -777,11 +782,24 @@ for _, item := range items {- `backend/app/migrations/sqlite/` — runs on `db.DB` (main)- `backend/app/migrations/sqlite_telemetry/` — runs on `db.TelemetryDB` (telemetry)-**SQLite-specific type helpers** (`backend/app/repositories/sqlite_types.go`):+**SQLite-specific type helpers** (`backend/app/repositories/telemetry/sqlitetypes/`):- `SQLiteTime` — implements `sql.Scanner`/`driver.Valuer` for `time.Time` ↔ SQLite TEXT- `SQLiteJSONMap` — implements `sql.Scanner`/`driver.Valuer` for `map[string]string` ↔ SQLite JSON TEXT- Row types (e.g., `endpointRow`, `taskRow`) wrap domain models with these types for lit compatibility+#### DuckDB Telemetry Backend (self-hosted, opt-in)++Built with `-tags telemetry_duckdb` (`CGO_ENABLED=1` required), this is an alternative telemetry store for the same `DB_TYPE=sqlite` deployment: the **main DB stays SQLite** (`db.DB`, relational/config), while the **telemetry DB becomes DuckDB** (`db.TelemetryDB`, columnar). It exists because DuckDB's columnar engine is dramatically faster on the analytics/aggregation reads the dashboard issues — at 10M rows it clears read-probe thresholds that SQLite times out on. Backends are selected on two build-tag axes: `telemetry_ch` / `telemetry_duckdb` / *(none = SQLite telemetry)* for the telemetry store and `transactional_pg` / *(none = SQLite main)* for the relational store. Only three combinations are supported — *(no tags)* dual SQLite, `telemetry_duckdb`, and `transactional_pg telemetry_ch` — enforced by compile-time guard files in `backend/app/db/` (stale `pgch`/`duckdb`/`oltp_*` tags also fail with a rename message). Repositories are organized on the same two axes: telemetry repositories live in per-backend packages `backend/app/repositories/telemetry/{clickhouse,sqlite,duckdb}/` and transactional (relational) repositories in `backend/app/repositories/transactional/{pg,sqlite}/`, each re-exported as singletons through tag-guarded facade files at the axis package root (`telemetry/telemetry_ch.go` etc., `transactional/transactional_pg.go` etc.). Consumers import the facade packages — `telemetry.SpanRepository`, `transactional.UserRepository` — never a backend package directly. Helpers shared by all telemetry backends are in `telemetry/shared/`, the SQLite scan/value types shared by the sqlite+duckdb backends are in `telemetry/sqlitetypes/`, and helpers/types shared by the transactional backends (auth-token hashing/time formats, facade-crossing structs) are in `transactional/shared/`. The `transactional/pg` and `transactional/sqlite` implementations are intentionally kept dialect-neutral (lit `:name` queries rendered per `db.Driver`), enforced byte-for-byte by `transactional/parity_test.go`. Running Postgres requires the `transactional_pg` build: the default build's migration runner applies SQLite-dialect migrations unconditionally, so `DB_TYPE=postgres` without the tag is not a supported combination.++- **Driver:** `github.com/duckdb/duckdb-go/v2` (the official driver; marcboeker/go-duckdb is deprecated). Bundles prebuilt static libs for glibc only — **not musl/Alpine**, so the image uses Debian (`Dockerfile.duckdb`).+- **Opened in** `backend/app/db/db_telemetry_duckdb.go`: telemetry path is the SQLite path with `.db` swapped for `_telemetry.duckdb`. By default DuckDB auto-tunes to the host; `DUCKDB_MEMORY_LIMIT`/`DUCKDB_THREADS`/`DUCKDB_CHECKPOINT_THRESHOLD` (passed through as DSN config options) let operators cap memory/threads so a memory-capped container doesn't read the host's RAM and OOM-kill the backend, and raise the WAL checkpoint threshold (default 16MB) so sustained Appender ingest isn't stalled by frequent checkpoints. `preserve_insertion_order=false` is always set — telemetry reads all have explicit ORDER BY, and dropping the guarantee lets DuckDB parallelize bulk loads and large scans with less memory. The read pool is bounded (`SetMaxOpenConns(duckDBMaxReadConns)`) since each DuckDB connection can use all threads + its own query memory; Appender writes use their own `DuckDBConnector.Connect()` connections and bypass that cap. Exposes `db.DuckDBConnector` (needed for the Appender).+- **Writes use the Appender API**, not `INSERT` (`duckdb.NewAppenderFromConn(conn, "", table)` → `AppendRow(...)` → `Close()` flushes). Upserts still go through `ExecContext` with `ON CONFLICT`. The Appender rejects typed `*string` for nullable VARCHAR — use `nullableString()` in `backend/app/repositories/telemetry/duckdb/helpers.go` (returns untyped `nil` or the dereferenced value).+- **Write-path observability:** a row the Appender rejects is dropped rather than failing the whole frame (the SQLite backend 500s instead), so a poison row cannot wedge the SDK's retry loop. Every drop increments a per-table counter (`db.RecordTelemetryRowDropped`) and fires a rate-limited (1/min per table) `traceway.CaptureException`; Appender flush/connect failures still propagate to the request (500, SDK retries) and increment an insert-failure counter. `GET /api/health/deep` (App auth, all telemetry backends) exposes `telemetryBackend`, `droppedRows` per table, `droppedRowsTotal`, `insertFailures`, and on DuckDB an `engine` object (db/WAL file bytes, `duckdb_memory()` usage, read-pool in-use/wait stats) alongside its existing ClickHouse fields; it 503s only when the configured telemetry backend is ClickHouse and CH is unreachable (the embedded backends answer 200 with `chReachable:false`). The benchmark loadgen polls it before/after every ramp step and fails any step whose drop delta is nonzero; read-probe fills record cumulative `droppedRows` per fill level. When `MONITORING_TRACEWAY_URL` is set, `monitoring.StartTelemetryDBReporter` also emits `traceway.duckdb.*` metrics every 10s: `rows_dropped.delta`, `insert_failures.delta`, `db_size_mb`, `wal_size_mb`, `memory_used_mb`, `read_pool.in_use`, `read_pool.wait_count.delta`, `read_pool.wait_ms.delta`. The hourly retention worker issues a `CHECKPOINT` after its deletes so retention actually reclaims disk (DuckDB otherwise defers reclamation to the WAL checkpoint threshold).+- **`lit` placeholders:** `db.Driver` stays `lit.SQLite`, which emits `?` — DuckDB accepts these, so no separate driver was needed for reads.+- **Migrations:** `backend/app/migrations/duckdb_telemetry/` (mirrors `sqlite_telemetry/` table-for-table; integer columns are `BIGINT`, JSON is `VARCHAR`, no secondary indexes since it's columnar).+- **Dialect gotchas vs SQLite** (the read queries differ): native `quantile_cont(col, p)` for P50/P95/P99 instead of fetch-and-sort; `strftime('%s',col)`→`epoch(col)`; time bucketing via `time_bucket(to_seconds(N), col, TIMESTAMP '1970-01-01')` — the explicit epoch origin is required because DuckDB anchors sub-day buckets at 2000-01-03 by default, which would misalign chart buckets against the SQLite backend's epoch-floored buckets for any interval that doesn't evenly divide a day; `json_extract`→`json_extract_string`; `json_each`→`LATERAL unnest(json_keys(x))`; strict GROUP BY needs `ANY_VALUE`/`arg_max`; `SUM` returns HUGEINT (CAST to BIGINT); `CAST(.. AS REAL)`→`CAST(.. AS DOUBLE)`.+- **Tests:** `backend/app/repositories/telemetry/testhelper_duckdb_test.go` (tagged `telemetry_duckdb`) provides `setupTestDB` so the entire existing telemetry test suite runs against an in-memory DuckDB.+#### Data RetentionRetention is handled in several different ways depending on the deployment.@@ -915,7 +933,7 @@ backend/app/migrations/ch/### Exception Hash Normalization-The backend normalizes stack traces before hashing to group identical errors despite different runtime values. This happens in `backend/app/repositories/exceptions.go`.+The backend normalizes stack traces before hashing to group identical errors despite different runtime values. This happens in `backend/app/controllers/clientcontrollers/client.controller.go`.**Normalization Steps:**1. Extract error type only (remove error message content)@@ -940,17 +958,17 @@ The backend normalizes stack traces before hashing to group identical errors des### Repository Patterns#### Singleton Pattern-Repositories are exported as package-level singletons for simple access:+Repositories are exported as package-level singletons, re-exported per storage axis through the facade packages `app/repositories/transactional` and `app/repositories/telemetry`:```go-// backend/app/repositories/users.go+// backend/app/repositories/transactional/sqlite/user.repository.go (and the pg/ twin)var UserRepository = userRepository{}-// backend/app/repositories/projects.go-var ProjectRepository = projectRepository{}+// backend/app/repositories/transactional/transactional_sqlite.go (tag-guarded facade)+var UserRepository = sqliterepo.UserRepository// Usage in controllers-user, err := repositories.UserRepository.FindByEmail(tx, email)-project, err := repositories.ProjectRepository.FindById(tx, id)+user, err := transactional.UserRepository.FindByEmail(tx, email)+spans, err := telemetry.SpanRepository.FindByTraceId(projectId, traceId)```#### Batch Insert (ClickHouse)@@ -1398,10 +1416,10 @@ type PaginationParams struct {1. **Ensure SDK captures metric** (or add to `traceway.go` metrics collection)-2. **Add repository query** in `backend/app/repositories/metrics.go`+2. **Add repository query** to each telemetry backend's `metric_point.repository.go` under `backend/app/repositories/telemetry/{clickhouse,sqlite,duckdb}/````go- func (r *MetricRepository) GetNewMetric(projectID uuid.UUID, from, to time.Time) ([]MetricPoint, error) {- // Query metric_records table+ func (r *metricPointRepository) GetNewMetric(ctx context.Context, projectId uuid.UUID, from, to time.Time) ([]models.TimeSeriesPoint, error) {+ // Query metric_points with the backend's dialect}```diff --git a/Dockerfile b/Dockerfileindex a1b69552..750fde1f 100644--- a/Dockerfile+++ b/Dockerfile@@ -36,7 +36,7 @@ RUN go mod edit -dropreplace=go.tracewayapp.com -dropreplace=go.tracewayapp.com/RUN go mod tidyRUN go mod download-RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -tags "pgch" -ldflags="-s -w" -o /traceway ./cmd/traceway+RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -tags "transactional_pg telemetry_ch" -ldflags="-s -w" -o /traceway ./cmd/traceway# ==============================================================================# Stage 3: ClickHouse binary sourcediff --git a/Dockerfile.duckdb b/Dockerfile.duckdbnew file mode 100644index 00000000..ff271784--- /dev/null+++ b/Dockerfile.duckdb@@ -0,0 +1,76 @@+# ==============================================================================+# Traceway DuckDB Docker Image+# Single binary serving API and Frontend with an embedded SQLite main DB and a+# DuckDB telemetry DB. No external databases required. Optional S3 for blobs.+#+# Unlike Dockerfile.sqlite (pure Go, Alpine, CGO_ENABLED=0), DuckDB requires+# CGO and links prebuilt glibc static libraries, so this image builds and runs+# on Debian (glibc), not Alpine (musl).+# ==============================================================================++# ==============================================================================+# Stage 1: Build Frontend+# ==============================================================================+FROM --platform=$BUILDPLATFORM node:22-alpine AS frontend-builder++WORKDIR /app/frontend++COPY frontend/package.json frontend/package-lock.json ./++RUN npm ci++COPY frontend/ ./++ENV CLOUD_MODE=false+RUN npm run build++# ==============================================================================+# Stage 2: Build Backend with embedded frontend (telemetry_duckdb tag = DuckDB telemetry)+# Built natively (no cross-compile) because CGO cross-compilation against the+# prebuilt DuckDB libraries is impractical; the benchmark SUT builds on-host.+# ==============================================================================+FROM golang:1.26-bookworm AS backend-builder++WORKDIR /app/backend++RUN apt-get update && apt-get install -y --no-install-recommends git build-essential && rm -rf /var/lib/apt/lists/*++COPY backend/ ./+COPY cli/ /app/cli/++COPY --from=frontend-builder /app/frontend/build ./static/frontend/++RUN go mod edit -dropreplace=go.tracewayapp.com -dropreplace=go.tracewayapp.com/tracewaygin+RUN go mod tidy+RUN go mod download++RUN CGO_ENABLED=1 go build -tags telemetry_duckdb -ldflags="-s -w" -o /traceway ./cmd/traceway++# ==============================================================================+# Stage 3: Runtime image (Debian slim for glibc + libstdc++)+# ==============================================================================+FROM debian:bookworm-slim++RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates tzdata wget libstdc++6 && rm -rf /var/lib/apt/lists/*++COPY --from=backend-builder /traceway /usr/local/bin/traceway++RUN mkdir -p /data && chmod 755 /data++WORKDIR /app++# DB_TYPE=sqlite selects the embedded codepath; in a telemetry_duckdb build that pairs a+# SQLite main DB (SQLITE_PATH) with a DuckDB telemetry DB derived alongside it+# (<path>_telemetry.duckdb). Both, plus local blob storage, live under /data.+ENV GIN_MODE=release \+ DB_TYPE=sqlite \+ SQLITE_PATH=/data/traceway.db \+ STORAGE_TYPE=local \+ STORAGE_PATH=/data/storage++EXPOSE 80 8082++HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \+ CMD wget -qO- http://localhost/health || exit 1++ENTRYPOINT ["/usr/local/bin/traceway"]diff --git a/Dockerfile.minimal b/Dockerfile.minimalindex cb2d855d..710fbc00 100644--- a/Dockerfile.minimal+++ b/Dockerfile.minimal@@ -47,7 +47,7 @@ RUN go mod tidyRUN go mod download# Build with embedded static files-RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -tags "pgch" -ldflags="-s -w" -o /traceway ./cmd/traceway+RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -tags "transactional_pg telemetry_ch" -ldflags="-s -w" -o /traceway ./cmd/traceway# ==============================================================================# Stage 3: Minimal runtime imagediff --git a/Dockerfile.sqlite b/Dockerfile.sqliteindex 3ce76120..5a9a3577 100644--- a/Dockerfile.sqlite+++ b/Dockerfile.sqlite@@ -21,7 +21,7 @@ ENV CLOUD_MODE=falseRUN npm run build# ==============================================================================-# Stage 2: Build Backend with embedded frontend (no pgch tag = SQLite mode)+# Stage 2: Build Backend with embedded frontend (no storage tags = SQLite mode)# ==============================================================================FROM --platform=$BUILDPLATFORM golang:1.26-alpine AS backend-builder@@ -38,8 +38,8 @@ RUN go mod edit -dropreplace=go.tracewayapp.com -dropreplace=go.tracewayapp.com/RUN go mod tidyRUN go mod download-# Build WITHOUT the pgch tag so the SQLite codepath in app/db/db_sqlite.go-# is selected. modernc.org/sqlite is pure Go, so CGO_ENABLED=0 is fine.+# Build WITHOUT storage tags so the SQLite codepaths in app/db/db_transactional_sqlite.go+# and db_telemetry_sqlite.go are selected. modernc.org/sqlite is pure Go, so CGO_ENABLED=0 is fine.ARG TARGETOSARG TARGETARCHRUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -ldflags="-s -w" -o /traceway ./cmd/tracewaydiff --git a/README.md b/README.mdindex 6da6511e..46913267 100644--- a/README.md+++ b/README.md@@ -236,29 +236,38 @@ Traceway integrates with the tools you already use. Every integration ships trac## Build Tags-| Tag | Purpose |-| ----------- | --------------------------------------------------------------------------------------------------------------- |-| _(none)_ | SQLite storage — embedded mode, zero dependencies. This is the default. |-| `pgch` | ClickHouse + PostgreSQL storage — standalone server mode. |-| `localdist` | Embeds frontend from `static/dist/` instead of `static/frontend/`. Used by traceway-cloud to inject billing UI. |+Storage is selected on two axes — the telemetry store and the transactional (relational) store:++| Tag | Purpose |+| ------------------ | --------------------------------------------------------------------------------------------------------------- |+| _(none)_ | SQLite storage on both axes — embedded mode, zero dependencies. This is the default. |+| `telemetry_duckdb` | DuckDB telemetry store — embedded mode with a columnar engine. Requires `CGO_ENABLED=1`. |+| `transactional_pg telemetry_ch` | ClickHouse (telemetry) + PostgreSQL (config) — standalone server mode. |+| `localdist` | Embeds frontend from `static/dist/` instead of `static/frontend/`. Used by traceway-cloud to inject billing UI. |```bash# Embedded mode (SQLite, default)cd backend && go build ./cmd/traceway+# Embedded mode with DuckDB telemetry+cd backend && CGO_ENABLED=1 go build -tags telemetry_duckdb ./cmd/traceway+# Standalone server (ClickHouse + PostgreSQL)-cd backend && go build -tags pgch ./cmd/traceway+cd backend && go build -tags "transactional_pg telemetry_ch" ./cmd/traceway```## Running Tests```bash# SQLite tests (default, no tags needed)-cd backend && go test -v -count=1 ./app/repositories/+cd backend && go test -v -count=1 ./app/repositories/...# ClickHouse + PostgreSQL tests (requires Docker)./scripts/test-backend-pgch.sh+# DuckDB telemetry tests+cd backend && CGO_ENABLED=1 go test -tags telemetry_duckdb -v -count=1 ./app/repositories/...+# OTEL trace converter tests (no DB required)cd backend && go test -v -count=1 ./app/controllers/otelcontrollers/diff --git a/backend/app/cache/project_cache.go b/backend/app/cache/project_cache.goindex d4d5f6ff..12677305 100644--- a/backend/app/cache/project_cache.go+++ b/backend/app/cache/project_cache.go@@ -9,7 +9,7 @@ import ("github.com/tracewayapp/traceway/backend/app/db""github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional""github.com/google/uuid")@@ -34,7 +34,7 @@ func (c *projectCache) Init(ctx context.Context) error {func (c *projectCache) Refresh(ctx context.Context) error {projects, err := db.ExecuteTransaction(func(tx *sql.Tx) ([]*models.Project, error) {- return repositories.ProjectRepository.FindAll(tx)+ return transactional.ProjectRepository.FindAll(tx)})if err != nil {return errdiff --git a/backend/app/chdb/batch_ctx.go b/backend/app/chdb/batch_ctx.goindex c5d58a5e..badeadad 100644--- a/backend/app/chdb/batch_ctx.go+++ b/backend/app/chdb/batch_ctx.go@@ -1,4 +1,4 @@-//go:build pgch+//go:build telemetry_chpackage chdbdiff --git a/backend/app/chdb/batch_retry.go b/backend/app/chdb/batch_retry.goindex fd0380c1..e330c566 100644--- a/backend/app/chdb/batch_retry.go+++ b/backend/app/chdb/batch_retry.go@@ -1,4 +1,4 @@-//go:build pgch+//go:build telemetry_chpackage chdbdiff --git a/backend/app/chdb/batch_retry_test.go b/backend/app/chdb/batch_retry_test.goindex b69e6d1d..b57140cb 100644--- a/backend/app/chdb/batch_retry_test.go+++ b/backend/app/chdb/batch_retry_test.go@@ -1,4 +1,4 @@-//go:build pgch+//go:build telemetry_chpackage chdbdiff --git a/backend/app/chdb/chdb.go b/backend/app/chdb/chdb.goindex debdab7a..8a12dcd2 100644--- a/backend/app/chdb/chdb.go+++ b/backend/app/chdb/chdb.go@@ -1,4 +1,4 @@-//go:build pgch+//go:build telemetry_chpackage chdbdiff --git a/backend/app/chdb/chdb_sqlite.go b/backend/app/chdb/chdb_stub.gosimilarity index 65%rename from backend/app/chdb/chdb_sqlite.gorename to backend/app/chdb/chdb_stub.goindex 9a0d1e1f..c3b713f6 100644--- a/backend/app/chdb/chdb_sqlite.go+++ b/backend/app/chdb/chdb_stub.go@@ -1,4 +1,4 @@-//go:build !pgch+//go:build !telemetry_chpackage chdbdiff --git a/backend/app/config/config.go b/backend/app/config/config.goindex 7c4976f1..b9df860d 100644--- a/backend/app/config/config.go+++ b/backend/app/config/config.go@@ -14,6 +14,10 @@ type Cfg struct {PostgresSSLMode stringSQLitePath string+ DuckDBMemoryLimit string+ DuckDBThreads string+ DuckDBCheckpointThreshold string+ClickhouseServer stringClickhouseDatabase stringClickhouseUsername string@@ -98,6 +102,10 @@ func LoadFromEnv() *Cfg {PostgresSSLMode: os.Getenv("POSTGRES_SSLMODE"),SQLitePath: os.Getenv("SQLITE_PATH"),+ DuckDBMemoryLimit: os.Getenv("DUCKDB_MEMORY_LIMIT"),+ DuckDBThreads: os.Getenv("DUCKDB_THREADS"),+ DuckDBCheckpointThreshold: os.Getenv("DUCKDB_CHECKPOINT_THRESHOLD"),+ClickhouseServer: os.Getenv("CLICKHOUSE_SERVER"),ClickhouseDatabase: os.Getenv("CLICKHOUSE_DATABASE"),ClickhouseUsername: os.Getenv("CLICKHOUSE_USERNAME"),diff --git a/backend/app/controllers/ai_trace.controller.go b/backend/app/controllers/ai_trace.controller.goindex d5ba0e2d..96bb6f39 100644--- a/backend/app/controllers/ai_trace.controller.go+++ b/backend/app/controllers/ai_trace.controller.go@@ -10,7 +10,7 @@ import ("github.com/google/uuid""github.com/tracewayapp/traceway/backend/app/middleware""github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry""github.com/tracewayapp/traceway/backend/app/storage"traceway "go.tracewayapp.com")@@ -63,7 +63,7 @@ func (a aiTraceController) FindGroupedByTraceName(c *gin.Context) {return}- stats, total, err := repositories.AiTraceRepository.FindGroupedByTraceName(c, projectId, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy, request.SortDirection, request.Search, request.RootFilter)+ stats, total, err := telemetry.AiTraceRepository.FindGroupedByTraceName(c, projectId, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy, request.SortDirection, request.Search, request.RootFilter)if err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading ai trace stats: %w", err))return@@ -104,13 +104,13 @@ func (a aiTraceController) FindByTraceName(c *gin.Context) {return}- traces, total, err := repositories.AiTraceRepository.FindByTraceName(c, projectId, traceName, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy, request.SortDirection)+ traces, total, err := telemetry.AiTraceRepository.FindByTraceName(c, projectId, traceName, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy, request.SortDirection)if err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading ai traces: %w", err))return}- stats, err := repositories.AiTraceRepository.GetTraceNameStats(c, projectId, traceName, request.FromDate, request.ToDate)+ stats, err := telemetry.AiTraceRepository.GetTraceNameStats(c, projectId, traceName, request.FromDate, request.ToDate)if err != nil {stats = nil}@@ -143,9 +143,9 @@ func (a aiTraceController) GetAiTraceDetail(c *gin.Context) {var request aiTraceDetailRequest_ = c.ShouldBindJSON(&request)- aiTrace, err := repositories.AiTraceRepository.FindById(c, projectId, traceId, request.RecordedAt)+ aiTrace, err := telemetry.AiTraceRepository.FindById(c, projectId, traceId, request.RecordedAt)if aiTrace == nil && err == nil && request.RecordedAt != nil {- aiTrace, err = repositories.AiTraceRepository.FindById(c, projectId, traceId, nil)+ aiTrace, err = telemetry.AiTraceRepository.FindById(c, projectId, traceId, nil)}if err != nil {c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("error loading ai trace: %w", err))diff --git a/backend/app/controllers/auth.controller.go b/backend/app/controllers/auth.controller.goindex 4209a6d8..11906d41 100644--- a/backend/app/controllers/auth.controller.go+++ b/backend/app/controllers/auth.controller.go@@ -1,14 +1,14 @@package controllersimport (+ "database/sql""github.com/tracewayapp/traceway/backend/app/cache""github.com/tracewayapp/traceway/backend/app/config""github.com/tracewayapp/traceway/backend/app/db""github.com/tracewayapp/traceway/backend/app/middleware""github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional""github.com/tracewayapp/traceway/backend/app/services"- "database/sql""net/http""github.com/gin-gonic/gin"@@ -21,7 +21,7 @@ type authController struct{}func (a authController) HasOrganizations(c *gin.Context) {tx := db.GetTx(c)- hasOrganizations, err := repositories.OrganizationRepository.HasOrganizations(tx)+ hasOrganizations, err := transactional.OrganizationRepository.HasOrganizations(tx)if err != nil {c.AbortWithError(http.StatusInternalServerError, err)@@ -45,7 +45,7 @@ func (a authController) Login(c *gin.Context) {tx := db.GetTx(c)- user, err := repositories.UserRepository.FindByEmail(tx, request.Email)+ user, err := transactional.UserRepository.FindByEmail(tx, request.Email)if err != nil {c.AbortWithError(http.StatusInternalServerError, err)return@@ -66,13 +66,13 @@ func (a authController) Login(c *gin.Context) {return}- projects, err := repositories.ProjectRepository.FindAllWithBackendUrlByUserId(tx, user.Id)+ projects, err := transactional.ProjectRepository.FindAllWithBackendUrlByUserId(tx, user.Id)if err != nil {c.AbortWithError(http.StatusInternalServerError, err)return}- organizations, err := repositories.OrganizationRepository.FindByUserIdWithRoles(tx, user.Id)+ organizations, err := transactional.OrganizationRepository.FindByUserIdWithRoles(tx, user.Id)if err != nil {c.AbortWithError(http.StatusInternalServerError, err)return@@ -109,7 +109,7 @@ func (a authController) Register(c *gin.Context) {// if we're not in the cloud mode only a single organization is allowedif config.Config.CloudMode != "true" {- hasOrganizations, err := repositories.OrganizationRepository.HasOrganizations(tx)+ hasOrganizations, err := transactional.OrganizationRepository.HasOrganizations(tx)if err != nil {c.AbortWithError(http.StatusInternalServerError, err)@@ -122,7 +122,7 @@ func (a authController) Register(c *gin.Context) {}}- exists, err := repositories.UserRepository.EmailExists(tx, request.Email)+ exists, err := transactional.UserRepository.EmailExists(tx, request.Email)if err != nil {c.AbortWithError(http.StatusInternalServerError, err)return@@ -138,19 +138,19 @@ func (a authController) Register(c *gin.Context) {return}- user, err := repositories.UserRepository.Create(tx, request.Email, request.Name, hashedPassword)+ user, err := transactional.UserRepository.Create(tx, request.Email, request.Name, hashedPassword)if err != nil {c.AbortWithError(http.StatusInternalServerError, err)return}- org, err := repositories.OrganizationRepository.Create(tx, request.OrganizationName, request.Timezone)+ org, err := transactional.OrganizationRepository.Create(tx, request.OrganizationName, request.Timezone)if err != nil {c.AbortWithError(http.StatusInternalServerError, err)return}- _, err = repositories.OrganizationRepository.AddUser(tx, org.Id, user.Id, "owner")+ _, err = transactional.OrganizationRepository.AddUser(tx, org.Id, user.Id, "owner")if err != nil {c.AbortWithError(http.StatusInternalServerError, err)return@@ -169,7 +169,7 @@ func (a authController) Register(c *gin.Context) {return}- project, err := repositories.ProjectRepository.CreateWithOrganization(tx, request.ProjectName, request.Framework, org.Id)+ project, err := transactional.ProjectRepository.CreateWithOrganization(tx, request.ProjectName, request.Framework, org.Id)if err != nil {c.AbortWithError(http.StatusInternalServerError, err)return@@ -181,7 +181,7 @@ func (a authController) Register(c *gin.Context) {return}- projects, err := repositories.ProjectRepository.FindAllWithBackendUrlByUserId(tx, user.Id)+ projects, err := transactional.ProjectRepository.FindAllWithBackendUrlByUserId(tx, user.Id)if err != nil {c.AbortWithError(http.StatusInternalServerError, err)return@@ -198,7 +198,7 @@ func (a authController) Register(c *gin.Context) {OrganizationId: project.OrganizationId,})- organizations, err := repositories.OrganizationRepository.FindByUserIdWithRoles(tx, user.Id)+ organizations, err := transactional.OrganizationRepository.FindByUserIdWithRoles(tx, user.Id)if err != nil {c.AbortWithError(http.StatusInternalServerError, err)return@@ -222,7 +222,7 @@ func (a authController) LoginBundle(c *gin.Context) {return}- user, err := repositories.UserRepository.FindById(tx, userId)+ user, err := transactional.UserRepository.FindById(tx, userId)if err != nil {c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("LoginBundle: load user: %w", err))return@@ -232,13 +232,13 @@ func (a authController) LoginBundle(c *gin.Context) {return}- projects, err := repositories.ProjectRepository.FindAllWithBackendUrlByUserId(tx, user.Id)+ projects, err := transactional.ProjectRepository.FindAllWithBackendUrlByUserId(tx, user.Id)if err != nil {c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("LoginBundle: load projects: %w", err))return}- organizations, err := repositories.OrganizationRepository.FindByUserIdWithRoles(tx, user.Id)+ organizations, err := transactional.OrganizationRepository.FindByUserIdWithRoles(tx, user.Id)if err != nil {c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("LoginBundle: load orgs: %w", err))returndiff --git a/backend/app/controllers/clientcontrollers/client.controller.go b/backend/app/controllers/clientcontrollers/client.controller.goindex 5bf25c90..3f42b4fd 100644--- a/backend/app/controllers/clientcontrollers/client.controller.go+++ b/backend/app/controllers/clientcontrollers/client.controller.go@@ -17,7 +17,7 @@ import ("github.com/tracewayapp/traceway/backend/app/models/clientmodels""github.com/tracewayapp/traceway/backend/app/monitoring""github.com/tracewayapp/traceway/backend/app/recordings"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry""github.com/tracewayapp/traceway/backend/app/services""github.com/tracewayapp/traceway/backend/app/symbolicator/sourcemap/jsstack"@@ -302,7 +302,7 @@ func (e clientController) Report(c *gin.Context) {if len(endpointsToInsert) > 0 {insertSpan := traceway.StartSpan(c, "report.insert.endpoints")- err := repositories.EndpointRepository.InsertAsync(c, endpointsToInsert)+ err := telemetry.EndpointRepository.InsertAsync(c, endpointsToInsert)insertSpan.End()if err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error inserting endpointsToInsert: %w", err))@@ -312,7 +312,7 @@ func (e clientController) Report(c *gin.Context) {if len(tasksToInsert) > 0 {insertSpan := traceway.StartSpan(c, "report.insert.tasks")- err := repositories.TaskRepository.InsertAsync(c, tasksToInsert)+ err := telemetry.TaskRepository.InsertAsync(c, tasksToInsert)insertSpan.End()if err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error inserting tasksToInsert: %w", err))@@ -322,7 +322,7 @@ func (e clientController) Report(c *gin.Context) {if len(sessionsToUpsert) > 0 {insertSpan := traceway.StartSpan(c, "report.upsert.sessions")- err := repositories.SessionRepository.Upsert(c, sessionsToUpsert)+ err := telemetry.SessionRepository.Upsert(c, sessionsToUpsert)insertSpan.End()if err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error upserting sessions: %w", err))@@ -331,7 +331,7 @@ func (e clientController) Report(c *gin.Context) {}exceptionInsertSpan := traceway.StartSpan(c, "report.insert.exceptions")- err = repositories.ExceptionStackTraceRepository.InsertAsync(c, exceptionStackTraceToInsert)+ err = telemetry.ExceptionStackTraceRepository.InsertAsync(c, exceptionStackTraceToInsert)exceptionInsertSpan.End()if err != nil {@@ -341,7 +341,7 @@ func (e clientController) Report(c *gin.Context) {if len(metricPointsToInsert) > 0 {insertSpan := traceway.StartSpan(c, "report.insert.metric_points")- err := repositories.MetricPointRepository.InsertAsync(c, metricPointsToInsert)+ err := telemetry.MetricPointRepository.InsertAsync(c, metricPointsToInsert)insertSpan.End()if err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error inserting metricPointsToInsert: %w", err))@@ -353,7 +353,7 @@ func (e clientController) Report(c *gin.Context) {}spanInsertSpan := traceway.StartSpan(c, "report.insert.spans")- err = repositories.SpanRepository.InsertAsync(c, spansToInsert)+ err = telemetry.SpanRepository.InsertAsync(c, spansToInsert)spanInsertSpan.End()if err != nil {diff --git a/backend/app/controllers/clientcontrollers/profile_ingest.controller.go b/backend/app/controllers/clientcontrollers/profile_ingest.controller.goindex 5ae968ca..9cacdfd3 100644--- a/backend/app/controllers/clientcontrollers/profile_ingest.controller.go+++ b/backend/app/controllers/clientcontrollers/profile_ingest.controller.go@@ -12,7 +12,7 @@ import ("github.com/tracewayapp/traceway/backend/app/models""github.com/tracewayapp/traceway/backend/app/monitoring""github.com/tracewayapp/traceway/backend/app/profiling"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry""github.com/tracewayapp/traceway/backend/app/storage"traceway "go.tracewayapp.com")@@ -73,15 +73,15 @@ func (e profileIngestController) Ingest(c *gin.Context) {convertMs := float64(time.Since(convertStart).Microseconds()) / 1000.0insertStart := time.Now()- if err := repositories.ProfileRepository.InsertStacksAsync(c, stacks); err != nil {+ if err := telemetry.ProfileRepository.InsertStacksAsync(c, stacks); err != nil {c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("error inserting profiling stacks: %w", err))return}- if err := repositories.ProfileRepository.InsertSamplesAsync(c, samples); err != nil {+ if err := telemetry.ProfileRepository.InsertSamplesAsync(c, samples); err != nil {c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("error inserting profiling samples: %w", err))return}- if err := repositories.ProfileRepository.InsertProfilesAsync(c, profiles); err != nil {+ if err := telemetry.ProfileRepository.InsertProfilesAsync(c, profiles); err != nil {c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("error inserting profiles: %w", err))return}diff --git a/backend/app/controllers/clientcontrollers/profile_ingest_controller_test.go b/backend/app/controllers/clientcontrollers/profile_ingest_controller_test.goindex 69dd5680..7f93da8c 100644--- a/backend/app/controllers/clientcontrollers/profile_ingest_controller_test.go+++ b/backend/app/controllers/clientcontrollers/profile_ingest_controller_test.go@@ -1,4 +1,4 @@-//go:build !pgch+//go:build !telemetry_ch && !telemetry_duckdbpackage clientcontrollersdiff --git a/backend/app/controllers/dashboard.controller.go b/backend/app/controllers/dashboard.controller.goindex c60dae1d..77f360f0 100644--- a/backend/app/controllers/dashboard.controller.go+++ b/backend/app/controllers/dashboard.controller.go@@ -2,7 +2,7 @@ package controllersimport ("github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry""net/http""sort""strings"@@ -33,7 +33,7 @@ func (d dashboardController) GetDashboardOverview(c *gin.Context) {// Get last 10 issues in the last 24 hours (only exceptions, not messages)span := traceway.StartSpan(c, "loading recent issues")- recentIssues, _, err := repositories.ExceptionStackTraceRepository.FindGrouped(c, projectId, start, now, 1, 10, "last_seen", "", "issues", false)+ recentIssues, _, err := telemetry.ExceptionStackTraceRepository.FindGrouped(c, projectId, start, now, 1, 10, "last_seen", "", "issues", false)span.End()if err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading recent issues: %w", err))@@ -42,7 +42,7 @@ func (d dashboardController) GetDashboardOverview(c *gin.Context) {// Get 10 worst performing endpointsspan = traceway.StartSpan(c, "loading worst endpoints")- worstEndpoints, err := repositories.EndpointRepository.FindWorstEndpoints(c, projectId, start, now, 10)+ worstEndpoints, err := telemetry.EndpointRepository.FindWorstEndpoints(c, projectId, start, now, 10)span.End()if err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading worst endpoints: %w", err))@@ -54,8 +54,8 @@ func (d dashboardController) GetDashboardOverview(c *gin.Context) {// Check if project has received ANY data (all time, not just 24h)var epoch time.Time // zero time = beginning of timespan = traceway.StartSpan(c, "checking project data")- endpointCount, _ := repositories.EndpointRepository.CountBetween(c, projectId, epoch, now)- exceptionCount, _ := repositories.ExceptionStackTraceRepository.CountBetween(c, projectId, epoch, now)+ endpointCount, _ := telemetry.EndpointRepository.CountBetween(c, projectId, epoch, now)+ exceptionCount, _ := telemetry.ExceptionStackTraceRepository.CountBetween(c, projectId, epoch, now)span.End()hasData = endpointCount > 0 || exceptionCount > 0}@@ -112,7 +112,7 @@ func (d dashboardController) GetDashboard(c *gin.Context) {intervalMinutes := calculateIntervalMinutes(duration)// Get available servers in the time range- availableServers, err := repositories.MetricPointRepository.GetDistinctServers(c, projectId, start, end)+ availableServers, err := telemetry.MetricPointRepository.GetDistinctServers(c, projectId, start, end)if err != nil {availableServers = []string{}}@@ -121,133 +121,133 @@ func (d dashboardController) GetDashboard(c *gin.Context) {// 1. Requests countspan := traceway.StartSpan(c, "loading requests trend")- requestsTrend, err := repositories.EndpointRepository.CountByInterval(c, projectId, start, end, intervalMinutes)+ requestsTrend, err := telemetry.EndpointRepository.CountByInterval(c, projectId, start, end, intervalMinutes)if err != nil {span.End()c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading requestsTrend: %w", err))return}- requestsCurrent, _ := repositories.EndpointRepository.CountBetween(c, projectId, start, end)- requestsPrev, _ := repositories.EndpointRepository.CountBetween(c, projectId, prevStart, prevEnd)+ requestsCurrent, _ := telemetry.EndpointRepository.CountBetween(c, projectId, start, end)+ requestsPrev, _ := telemetry.EndpointRepository.CountBetween(c, projectId, prevStart, prevEnd)span.End()metrics = append(metrics, buildMetric("requests", "Requests", float64(requestsCurrent), "count", requestsTrend, float64(requestsPrev), "requests"))// 2. Exceptions countspan = traceway.StartSpan(c, "loading exceptions trend")- exceptionsTrend, err := repositories.ExceptionStackTraceRepository.CountByInterval(c, projectId, start, end, intervalMinutes)+ exceptionsTrend, err := telemetry.ExceptionStackTraceRepository.CountByInterval(c, projectId, start, end, intervalMinutes)if err != nil {span.End()c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading exceptionsTrend: %w", err))return}- exceptionsCurrent, _ := repositories.ExceptionStackTraceRepository.CountBetween(c, projectId, start, end)- exceptionsPrev, _ := repositories.ExceptionStackTraceRepository.CountBetween(c, projectId, prevStart, prevEnd)+ exceptionsCurrent, _ := telemetry.ExceptionStackTraceRepository.CountBetween(c, projectId, start, end)+ exceptionsPrev, _ := telemetry.ExceptionStackTraceRepository.CountBetween(c, projectId, prevStart, prevEnd)span.End()metrics = append(metrics, buildMetric("exceptions", "Exceptions", float64(exceptionsCurrent), "count", exceptionsTrend, float64(exceptionsPrev), "exceptions"))// 3. Average Response Timespan = traceway.StartSpan(c, "loading avg response time")- avgDurationTrend, err := repositories.EndpointRepository.AvgDurationByInterval(c, projectId, start, end, intervalMinutes)+ avgDurationTrend, err := telemetry.EndpointRepository.AvgDurationByInterval(c, projectId, start, end, intervalMinutes)if err != nil {span.End()c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading avgDurationTrend: %w", err))return}avgDurationCurrent := getLastValue(avgDurationTrend)- avgDurationPrevTrend, _ := repositories.EndpointRepository.AvgDurationByInterval(c, projectId, prevStart, prevEnd, intervalMinutes)+ avgDurationPrevTrend, _ := telemetry.EndpointRepository.AvgDurationByInterval(c, projectId, prevStart, prevEnd, intervalMinutes)avgDurationPrev := getAverageValue(avgDurationPrevTrend)span.End()metrics = append(metrics, buildMetric("avg_response_time", "Avg Response Time", avgDurationCurrent, "ms", avgDurationTrend, avgDurationPrev, "response_time"))// 4. Error Ratespan = traceway.StartSpan(c, "loading error rate")- errorRateTrend, err := repositories.EndpointRepository.ErrorRateByInterval(c, projectId, start, end, intervalMinutes)+ errorRateTrend, err := telemetry.EndpointRepository.ErrorRateByInterval(c, projectId, start, end, intervalMinutes)if err != nil {span.End()c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading errorRateTrend: %w", err))return}errorRateCurrent := getLastValue(errorRateTrend)- errorRatePrevTrend, _ := repositories.EndpointRepository.ErrorRateByInterval(c, projectId, prevStart, prevEnd, intervalMinutes)+ errorRatePrevTrend, _ := telemetry.EndpointRepository.ErrorRateByInterval(c, projectId, prevStart, prevEnd, intervalMinutes)errorRatePrev := getAverageValue(errorRatePrevTrend)span.End()metrics = append(metrics, buildMetric("error_rate", "Error Rate", errorRateCurrent, "%", errorRateTrend, errorRatePrev, "error_rate"))// 5. CPU Usagespan = traceway.StartSpan(c, "loading cpu usage")- cpuPerServer, err := repositories.MetricPointRepository.GetAverageByIntervalPerServer(c, projectId, models.MetricNameCpuUsage, start, end, intervalMinutes, selectedServers)+ cpuPerServer, err := telemetry.MetricPointRepository.GetAverageByIntervalPerServer(c, projectId, models.MetricNameCpuUsage, start, end, intervalMinutes, selectedServers)if err != nil {span.End()c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading cpuPerServer: %w", err))return}- cpuPrev, _ := repositories.MetricPointRepository.GetAverageBetween(c, projectId, models.MetricNameCpuUsage, prevStart, prevEnd)+ cpuPrev, _ := telemetry.MetricPointRepository.GetAverageBetween(c, projectId, models.MetricNameCpuUsage, prevStart, prevEnd)span.End()metrics = append(metrics, buildMetricWithServers("cpu_usage", "CPU Usage", "%", cpuPerServer, cpuPrev, "cpu"))// 6. Memory Usage (MB)span = traceway.StartSpan(c, "loading memory usage")- memPerServer, err := repositories.MetricPointRepository.GetAverageByIntervalPerServer(c, projectId, models.MetricNameMemoryUsage, start, end, intervalMinutes, selectedServers)+ memPerServer, err := telemetry.MetricPointRepository.GetAverageByIntervalPerServer(c, projectId, models.MetricNameMemoryUsage, start, end, intervalMinutes, selectedServers)if err != nil {span.End()c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading memPerServer: %w", err))return}- memPrev, _ := repositories.MetricPointRepository.GetAverageBetween(c, projectId, models.MetricNameMemoryUsage, prevStart, prevEnd)+ memPrev, _ := telemetry.MetricPointRepository.GetAverageBetween(c, projectId, models.MetricNameMemoryUsage, prevStart, prevEnd)span.End()metrics = append(metrics, buildMetricWithServers("memory_usage", "Memory Usage", "MB", memPerServer, memPrev, "memory"))// 7. Total System Memory (MB)span = traceway.StartSpan(c, "loading total memory")- memTotalPerServer, err := repositories.MetricPointRepository.GetAverageByIntervalPerServer(c, projectId, models.MetricNameMemoryTotal, start, end, intervalMinutes, selectedServers)+ memTotalPerServer, err := telemetry.MetricPointRepository.GetAverageByIntervalPerServer(c, projectId, models.MetricNameMemoryTotal, start, end, intervalMinutes, selectedServers)if err != nil {span.End()c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading memTotalPerServer: %w", err))return}- memTotalPrev, _ := repositories.MetricPointRepository.GetAverageBetween(c, projectId, models.MetricNameMemoryTotal, prevStart, prevEnd)+ memTotalPrev, _ := telemetry.MetricPointRepository.GetAverageBetween(c, projectId, models.MetricNameMemoryTotal, prevStart, prevEnd)span.End()metrics = append(metrics, buildMetricWithServers("memory_total", "Total Memory", "MB", memTotalPerServer, memTotalPrev, "memory_total"))// 8. Go Routinesspan = traceway.StartSpan(c, "loading go routines")- goRoutinesPerServer, err := repositories.MetricPointRepository.GetAverageByIntervalPerServer(c, projectId, models.MetricNameGoRoutines, start, end, intervalMinutes, selectedServers)+ goRoutinesPerServer, err := telemetry.MetricPointRepository.GetAverageByIntervalPerServer(c, projectId, models.MetricNameGoRoutines, start, end, intervalMinutes, selectedServers)if err != nil {span.End()c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading goRoutinesPerServer: %w", err))return}- goRoutinesPrev, _ := repositories.MetricPointRepository.GetAverageBetween(c, projectId, models.MetricNameGoRoutines, prevStart, prevEnd)+ goRoutinesPrev, _ := telemetry.MetricPointRepository.GetAverageBetween(c, projectId, models.MetricNameGoRoutines, prevStart, prevEnd)span.End()metrics = append(metrics, buildMetricWithServers("go_routines", "Go Routines", "", goRoutinesPerServer, goRoutinesPrev, "go_routines"))// 9. Heap Objectsspan = traceway.StartSpan(c, "loading heap objects")- heapObjectsPerServer, err := repositories.MetricPointRepository.GetAverageByIntervalPerServer(c, projectId, models.MetricNameHeapObjects, start, end, intervalMinutes, selectedServers)+ heapObjectsPerServer, err := telemetry.MetricPointRepository.GetAverageByIntervalPerServer(c, projectId, models.MetricNameHeapObjects, start, end, intervalMinutes, selectedServers)if err != nil {span.End()c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading heapObjectsPerServer: %w", err))return}- heapObjectsPrev, _ := repositories.MetricPointRepository.GetAverageBetween(c, projectId, models.MetricNameHeapObjects, prevStart, prevEnd)+ heapObjectsPrev, _ := telemetry.MetricPointRepository.GetAverageBetween(c, projectId, models.MetricNameHeapObjects, prevStart, prevEnd)span.End()metrics = append(metrics, buildMetricWithServers("heap_objects", "Heap Objects", "", heapObjectsPerServer, heapObjectsPrev, "heap_objects"))// 10. Num GCspan = traceway.StartSpan(c, "loading gc cycles")- numGCPerServer, err := repositories.MetricPointRepository.GetAverageByIntervalPerServer(c, projectId, models.MetricNameNumGC, start, end, intervalMinutes, selectedServers)+ numGCPerServer, err := telemetry.MetricPointRepository.GetAverageByIntervalPerServer(c, projectId, models.MetricNameNumGC, start, end, intervalMinutes, selectedServers)if err != nil {span.End()c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading numGCPerServer: %w", err))return}- numGCPrev, _ := repositories.MetricPointRepository.GetAverageBetween(c, projectId, models.MetricNameNumGC, prevStart, prevEnd)+ numGCPrev, _ := telemetry.MetricPointRepository.GetAverageBetween(c, projectId, models.MetricNameNumGC, prevStart, prevEnd)span.End()metrics = append(metrics, buildMetricWithServers("num_gc", "GC Cycles", "", numGCPerServer, numGCPrev, "num_gc"))// 11. GC Pause Total (convert from nanoseconds to milliseconds)span = traceway.StartSpan(c, "loading gc pause")- gcPausePerServer, err := repositories.MetricPointRepository.GetAverageByIntervalPerServer(c, projectId, models.MetricNameGCPauseTotal, start, end, intervalMinutes, selectedServers)+ gcPausePerServer, err := telemetry.MetricPointRepository.GetAverageByIntervalPerServer(c, projectId, models.MetricNameGCPauseTotal, start, end, intervalMinutes, selectedServers)if err != nil {span.End()c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading gcPausePerServer: %w", err))@@ -259,7 +259,7 @@ func (d dashboardController) GetDashboard(c *gin.Context) {gcPausePerServer[serverName][i].Value = points[i].Value / 1_000_000}}- gcPausePrevRaw, _ := repositories.MetricPointRepository.GetAverageBetween(c, projectId, models.MetricNameGCPauseTotal, prevStart, prevEnd)+ gcPausePrevRaw, _ := telemetry.MetricPointRepository.GetAverageBetween(c, projectId, models.MetricNameGCPauseTotal, prevStart, prevEnd)span.End()gcPausePrev := gcPausePrevRaw / 1_000_000metrics = append(metrics, buildMetricWithServers("gc_pause", "GC Pause", "ms", gcPausePerServer, gcPausePrev, "gc_pause"))diff --git a/backend/app/controllers/device_auth.controller.go b/backend/app/controllers/device_auth.controller.goindex b8ff0ef7..373cac42 100644--- a/backend/app/controllers/device_auth.controller.go+++ b/backend/app/controllers/device_auth.controller.go@@ -11,7 +11,7 @@ import ("github.com/tracewayapp/traceway/backend/app/db""github.com/tracewayapp/traceway/backend/app/middleware""github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional""github.com/tracewayapp/traceway/backend/app/services/authserver")@@ -100,7 +100,7 @@ func (c *deviceAuthController) Lookup(ctx *gin.Context) {return}- da, err := repositories.DeviceAuthorizationRepository.FindByUserCode(db.DB, userCode)+ da, err := transactional.DeviceAuthorizationRepository.FindByUserCode(db.DB, userCode)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("device lookup: %w", err))returndiff --git a/backend/app/controllers/distributed_trace.controller.go b/backend/app/controllers/distributed_trace.controller.goindex 9841713f..eff605db 100644--- a/backend/app/controllers/distributed_trace.controller.go+++ b/backend/app/controllers/distributed_trace.controller.go@@ -9,7 +9,8 @@ import ("github.com/tracewayapp/traceway/backend/app/db""github.com/tracewayapp/traceway/backend/app/middleware""github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional""github.com/gin-gonic/gin""github.com/google/uuid"@@ -52,7 +53,7 @@ func (d distributedTraceController) GetDistributedTrace(c *gin.Context) {userId := middleware.GetUserId(c)projects, err := db.ExecuteTransaction(func(tx *sql.Tx) ([]*models.Project, error) {- return repositories.ProjectRepository.FindByUserId(tx, userId)+ return transactional.ProjectRepository.FindByUserId(tx, userId)})if err != nil {c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to load user projects: %w", err))@@ -76,25 +77,25 @@ func (d distributedTraceController) GetDistributedTrace(c *gin.Context) {ctx := context.Background()- endpoints, err := repositories.EndpointRepository.FindByDistributedTraceId(ctx, distributedTraceId, projectIds, request.RecordedAt)+ endpoints, err := telemetry.EndpointRepository.FindByDistributedTraceId(ctx, distributedTraceId, projectIds, request.RecordedAt)if err != nil {c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to query endpoints: %w", err))return}- tasks, err := repositories.TaskRepository.FindByDistributedTraceId(ctx, distributedTraceId, projectIds, request.RecordedAt)+ tasks, err := telemetry.TaskRepository.FindByDistributedTraceId(ctx, distributedTraceId, projectIds, request.RecordedAt)if err != nil {c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to query tasks: %w", err))return}- aiTraces, err := repositories.AiTraceRepository.FindByDistributedTraceId(ctx, distributedTraceId, projectIds, request.RecordedAt)+ aiTraces, err := telemetry.AiTraceRepository.FindByDistributedTraceId(ctx, distributedTraceId, projectIds, request.RecordedAt)if err != nil {c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to query ai traces: %w", err))return}- exceptions, err := repositories.ExceptionStackTraceRepository.FindByDistributedTraceId(ctx, distributedTraceId, projectIds, request.RecordedAt)+ exceptions, err := telemetry.ExceptionStackTraceRepository.FindByDistributedTraceId(ctx, distributedTraceId, projectIds, request.RecordedAt)if err != nil {c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to query exceptions: %w", err))returndiff --git a/backend/app/controllers/endpoint.controller.go b/backend/app/controllers/endpoint.controller.goindex 7c90d62a..593b52e4 100644--- a/backend/app/controllers/endpoint.controller.go+++ b/backend/app/controllers/endpoint.controller.go@@ -1,11 +1,11 @@package controllersimport (- "github.com/tracewayapp/traceway/backend/app/middleware"- "github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/repositories""database/sql""errors"+ "github.com/tracewayapp/traceway/backend/app/middleware"+ "github.com/tracewayapp/traceway/backend/app/models"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry""net/http""net/url""time"@@ -61,7 +61,7 @@ func (e endpointController) FindAllEndpoints(c *gin.Context) {}span := traceway.StartSpan(c, "loading endpoints")- endpoints, total, err := repositories.EndpointRepository.FindAll(c, projectId, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy)+ endpoints, total, err := telemetry.EndpointRepository.FindAll(c, projectId, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy)span.End()if err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading endpoints: %w", err))@@ -93,7 +93,7 @@ func (e endpointController) FindGroupedByEndpoint(c *gin.Context) {}span := traceway.StartSpan(c, "loading grouped endpoints")- stats, total, err := repositories.EndpointRepository.FindGroupedByEndpoint(c, projectId, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy, request.SortDirection, request.Search, request.RootFilter)+ stats, total, err := telemetry.EndpointRepository.FindGroupedByEndpoint(c, projectId, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy, request.SortDirection, request.Search, request.RootFilter)span.End()if err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading stats: %w", err))@@ -137,7 +137,7 @@ func (e endpointController) FindByEndpoint(c *gin.Context) {}span := traceway.StartSpan(c, "loading endpoint instances")- endpoints, total, err := repositories.EndpointRepository.FindByEndpoint(c, projectId, endpoint, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy, request.SortDirection)+ endpoints, total, err := telemetry.EndpointRepository.FindByEndpoint(c, projectId, endpoint, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy, request.SortDirection)span.End()if err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading endpoints: %w", err))@@ -146,7 +146,7 @@ func (e endpointController) FindByEndpoint(c *gin.Context) {// Get aggregate stats for this endpointspan = traceway.StartSpan(c, "loading endpoint stats")- stats, err := repositories.EndpointRepository.GetEndpointStats(c, projectId, endpoint, request.FromDate, request.ToDate)+ stats, err := telemetry.EndpointRepository.GetEndpointStats(c, projectId, endpoint, request.FromDate, request.ToDate)span.End()if err != nil {// Don't fail the request if stats fail, just return nil stats@@ -189,7 +189,7 @@ func (e endpointController) GetStackedChart(c *gin.Context) {}span := traceway.StartSpan(c, "loading stacked chart")- data, err := repositories.EndpointRepository.GetEndpointStackedChart(c, projectId, request.FromDate, request.ToDate, request.IntervalMinutes, request.MetricType)+ data, err := telemetry.EndpointRepository.GetEndpointStackedChart(c, projectId, request.FromDate, request.ToDate, request.IntervalMinutes, request.MetricType)span.End()if err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading stacked chart data: %w", err))@@ -217,7 +217,7 @@ func (e endpointController) GetSlowEndpoint(c *gin.Context) {endpoint = rawEndpoint}- offsetMs, reason, err := repositories.EndpointRepository.GetSlowEndpoint(c, projectId, endpoint)+ offsetMs, reason, err := telemetry.EndpointRepository.GetSlowEndpoint(c, projectId, endpoint)if errors.Is(err, sql.ErrNoRows) {c.JSON(http.StatusOK, gin.H{"offsetMs": 0, "reason": ""})return@@ -249,7 +249,7 @@ func (e endpointController) SetSlowEndpoint(c *gin.Context) {return}- if err := repositories.EndpointRepository.UpsertSlowEndpoint(c, projectId, request.Endpoint, request.OffsetMs, request.Reason); err != nil {+ if err := telemetry.EndpointRepository.UpsertSlowEndpoint(c, projectId, request.Endpoint, request.OffsetMs, request.Reason); err != nil {c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("error saving slow endpoint: %w", err))return}diff --git a/backend/app/controllers/endpoint_detail.controller.go b/backend/app/controllers/endpoint_detail.controller.goindex 5ec5585e..caeac17a 100644--- a/backend/app/controllers/endpoint_detail.controller.go+++ b/backend/app/controllers/endpoint_detail.controller.go@@ -6,7 +6,7 @@ import ("github.com/tracewayapp/traceway/backend/app/middleware""github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry""github.com/gin-gonic/gin""github.com/google/uuid"@@ -59,9 +59,9 @@ func (t endpointDetailController) GetEndpointDetail(c *gin.Context) {// Get endpointspan := traceway.StartSpan(c, "loading endpoint")- endpoint, err := repositories.EndpointRepository.FindById(c, projectId, endpointId, request.RecordedAt)+ endpoint, err := telemetry.EndpointRepository.FindById(c, projectId, endpointId, request.RecordedAt)if endpoint == nil && err == nil && request.RecordedAt != nil {- endpoint, err = repositories.EndpointRepository.FindById(c, projectId, endpointId, nil)+ endpoint, err = telemetry.EndpointRepository.FindById(c, projectId, endpointId, nil)}span.End()if err != nil {@@ -77,7 +77,7 @@ func (t endpointDetailController) GetEndpointDetail(c *gin.Context) {// Get spans (flat list ordered by start_time)span = traceway.StartSpan(c, "loading spans")- spans, err := repositories.SpanRepository.FindByTraceId(c, projectId, endpointId, &recordedAt)+ spans, err := telemetry.SpanRepository.FindByTraceId(c, projectId, endpointId, &recordedAt)span.End()if err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading spans: %w", err))@@ -89,7 +89,7 @@ func (t endpointDetailController) GetEndpointDetail(c *gin.Context) {var messages []EndpointMessageInfospan = traceway.StartSpan(c, "loading exceptions")- allExceptions, err := repositories.ExceptionStackTraceRepository.FindAllByTraceId(c, projectId, endpointId, &recordedAt)+ allExceptions, err := telemetry.ExceptionStackTraceRepository.FindAllByTraceId(c, projectId, endpointId, &recordedAt)span.End()if err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading all exceptions: %w", err))diff --git a/backend/app/controllers/exception_stack_trace.controller.go b/backend/app/controllers/exception_stack_trace.controller.goindex 97c16696..a1e7615f 100644--- a/backend/app/controllers/exception_stack_trace.controller.go+++ b/backend/app/controllers/exception_stack_trace.controller.go@@ -13,7 +13,7 @@ import ("github.com/tracewayapp/traceway/backend/app/middleware""github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry""github.com/tracewayapp/traceway/backend/app/storage""github.com/gin-gonic/gin"@@ -91,7 +91,7 @@ func (e exceptionStackTraceController) FindGrouppedExceptionStackTraces(c *gin.C}span := traceway.StartSpan(c, "loading grouped exceptions")- exceptions, total, err := repositories.ExceptionStackTraceRepository.FindGrouped(c, projectId, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy, request.Search, request.SearchType, request.IncludeArchived)+ exceptions, total, err := telemetry.ExceptionStackTraceRepository.FindGrouped(c, projectId, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy, request.Search, request.SearchType, request.IncludeArchived)span.End()if err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading exceptions: %w", err))@@ -109,7 +109,7 @@ func (e exceptionStackTraceController) FindGrouppedExceptionStackTraces(c *gin.Cstart24h := now.Add(-24 * time.Hour)span = traceway.StartSpan(c, "loading hourly trends")- trends, err := repositories.ExceptionStackTraceRepository.GetHourlyTrendForHashes(c, projectId, hashes, start24h, now)+ trends, err := telemetry.ExceptionStackTraceRepository.GetHourlyTrendForHashes(c, projectId, hashes, start24h, now)span.End()if err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading trends: %w", err))@@ -157,7 +157,7 @@ func (e exceptionStackTraceController) FindByHash(c *gin.Context) {}span := traceway.StartSpan(c, "loading exception by hash")- group, occurrences, total, err := repositories.ExceptionStackTraceRepository.FindByHash(c, projectId, exceptionHash, request.Pagination.Page, request.Pagination.PageSize)+ group, occurrences, total, err := telemetry.ExceptionStackTraceRepository.FindByHash(c, projectId, exceptionHash, request.Pagination.Page, request.Pagination.PageSize)span.End()if err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading the group: %w", err))@@ -184,7 +184,7 @@ func (e exceptionStackTraceController) FindByHash(c *gin.Context) {// The per-exception 10 s clip and the parent session are independent// attachments — surface both whenever they exist. The dashboard plays// the clip inline and renders a link to the full session.- filePath, err := repositories.SessionRecordingRepository.FindByExceptionId(c, projectId, occurrences[0].Id)+ filePath, err := telemetry.SessionRecordingRepository.FindByExceptionId(c, projectId, occurrences[0].Id)if err == nil && filePath != "" {recording, err := loadSessionRecording(c, filePath)if err == nil {@@ -196,7 +196,7 @@ func (e exceptionStackTraceController) FindByHash(c *gin.Context) {traceway.CaptureException(fmt.Errorf("failed to load session recording ref for exception %s: %w", occurrences[0].Id, err))}- sessionId, err := repositories.ExceptionStackTraceRepository.GetSessionIdForException(c, projectId, occurrences[0].Id)+ sessionId, err := telemetry.ExceptionStackTraceRepository.GetSessionIdForException(c, projectId, occurrences[0].Id)if err == nil && sessionId != nil {response.SessionId = sessionId}@@ -223,7 +223,7 @@ func (e exceptionStackTraceController) ArchiveExceptions(c *gin.Context) {return}- err = repositories.ExceptionStackTraceRepository.ArchiveByHashes(c, projectId, request.Hashes)+ err = telemetry.ExceptionStackTraceRepository.ArchiveByHashes(c, projectId, request.Hashes)if err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error archiving %s: %w", strings.Join(request.Hashes, ","), err))return@@ -250,7 +250,7 @@ func (e exceptionStackTraceController) UnarchiveExceptions(c *gin.Context) {return}- err = repositories.ExceptionStackTraceRepository.UnarchiveByHashes(c, projectId, request.Hashes)+ err = telemetry.ExceptionStackTraceRepository.UnarchiveByHashes(c, projectId, request.Hashes)if err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error unarchiving %s: %w", strings.Join(request.Hashes, ","), err))return@@ -280,9 +280,9 @@ func (e exceptionStackTraceController) FindById(c *gin.Context) {_ = c.ShouldBindJSON(&request)span := traceway.StartSpan(c, "loading exception by id")- exception, err := repositories.ExceptionStackTraceRepository.FindById(c, projectId, exceptionId, request.RecordedAt)+ exception, err := telemetry.ExceptionStackTraceRepository.FindById(c, projectId, exceptionId, request.RecordedAt)if exception == nil && err == nil && request.RecordedAt != nil {- exception, err = repositories.ExceptionStackTraceRepository.FindById(c, projectId, exceptionId, nil)+ exception, err = telemetry.ExceptionStackTraceRepository.FindById(c, projectId, exceptionId, nil)}span.End()if err != nil {@@ -297,7 +297,7 @@ func (e exceptionStackTraceController) FindById(c *gin.Context) {response := gin.H{"exception": exception}- filePath, err := repositories.SessionRecordingRepository.FindByExceptionId(c, projectId, exceptionId)+ filePath, err := telemetry.SessionRecordingRepository.FindByExceptionId(c, projectId, exceptionId)if err == nil && filePath != "" {recording, err := loadSessionRecording(c, filePath)if err == nil {@@ -309,7 +309,7 @@ func (e exceptionStackTraceController) FindById(c *gin.Context) {traceway.CaptureException(fmt.Errorf("failed to load session recording ref for exception %s: %w", exceptionId, err))}- sessionId, err := repositories.ExceptionStackTraceRepository.GetSessionIdForException(c, projectId, exceptionId)+ sessionId, err := telemetry.ExceptionStackTraceRepository.GetSessionIdForException(c, projectId, exceptionId)if err == nil && sessionId != nil {response["sessionId"] = sessionId}diff --git a/backend/app/controllers/health_deep.go b/backend/app/controllers/health_deep.goindex efbb6d69..a18d2398 100644--- a/backend/app/controllers/health_deep.go+++ b/backend/app/controllers/health_deep.go@@ -4,6 +4,7 @@ import ("net/http""github.com/gin-gonic/gin"+ "github.com/tracewayapp/traceway/backend/app/db")type healthDeepController struct{}@@ -29,11 +30,30 @@ type HealthDeepResponse struct {ErrorsRecent []CHError `json:"errorsRecent,omitempty"`MemoryUsageBytes int64 `json:"memoryUsageBytes,omitempty"`MemoryTotalBytes int64 `json:"memoryTotalBytes,omitempty"`++ TelemetryBackend string `json:"telemetryBackend"`+ DroppedRows map[string]uint64 `json:"droppedRows"`+ DroppedRowsTotal uint64 `json:"droppedRowsTotal"`+ InsertFailures uint64 `json:"insertFailures"`+ Engine *db.TelemetryEngineStats `json:"engine,omitempty"`}+// 503 means the configured telemetry backend is down. On the embedded+// backends chReachable stays false with a 200, which is what the loadgen's+// merge-idle fast path keys on.func (h healthDeepController) Get(c *gin.Context) {resp := fetchCHHealth(c.Request.Context())- if !resp.CHReachable {++ dropped, droppedTotal, insertFailures := db.GetTelemetryIngestCounters()+ resp.TelemetryBackend = db.TelemetryBackendName()+ resp.DroppedRows = dropped+ resp.DroppedRowsTotal = droppedTotal+ resp.InsertFailures = insertFailures+ if engine, ok := db.GetTelemetryEngineStats(c.Request.Context()); ok {+ resp.Engine = &engine+ }++ if resp.TelemetryBackend == "clickhouse" && !resp.CHReachable {c.JSON(http.StatusServiceUnavailable, resp)return}diff --git a/backend/app/controllers/health_deep_pgch.go b/backend/app/controllers/health_deep_ch.gosimilarity index 98%rename from backend/app/controllers/health_deep_pgch.gorename to backend/app/controllers/health_deep_ch.goindex 173e224b..01336c92 100644--- a/backend/app/controllers/health_deep_pgch.go+++ b/backend/app/controllers/health_deep_ch.go@@ -1,4 +1,4 @@-//go:build pgch+//go:build telemetry_chpackage controllersdiff --git a/backend/app/controllers/health_deep_sqlite.go b/backend/app/controllers/health_deep_stub.gosimilarity index 85%rename from backend/app/controllers/health_deep_sqlite.gorename to backend/app/controllers/health_deep_stub.goindex ace2d896..6c5b21bf 100644--- a/backend/app/controllers/health_deep_sqlite.go+++ b/backend/app/controllers/health_deep_stub.go@@ -1,4 +1,4 @@-//go:build !pgch+//go:build !telemetry_chpackage controllersdiff --git a/backend/app/controllers/invitation.controller.go b/backend/app/controllers/invitation.controller.goindex 0e9bcbe7..de8ca478 100644--- a/backend/app/controllers/invitation.controller.go+++ b/backend/app/controllers/invitation.controller.go@@ -1,14 +1,14 @@package controllersimport (- "github.com/tracewayapp/traceway/backend/app/middleware"- "github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/db"- "github.com/tracewayapp/traceway/backend/app/repositories"- "github.com/tracewayapp/traceway/backend/app/services""database/sql""errors""fmt"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/middleware"+ "github.com/tracewayapp/traceway/backend/app/models"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional"+ "github.com/tracewayapp/traceway/backend/app/services""net/http""strconv""time"@@ -33,7 +33,7 @@ func (c *invitationController) InviteUser(ctx *gin.Context) {return}- isMember, err := repositories.OrganizationRepository.IsUserMemberByEmail(tx, organizationId, request.Email)+ isMember, err := transactional.OrganizationRepository.IsUserMemberByEmail(tx, organizationId, request.Email)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to check membership: %w", err))return@@ -43,7 +43,7 @@ func (c *invitationController) InviteUser(ctx *gin.Context) {return}- hasPending, err := repositories.InvitationRepository.HasPendingInvitation(tx, request.Email, organizationId)+ hasPending, err := transactional.InvitationRepository.HasPendingInvitation(tx, request.Email, organizationId)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to check pending invitations: %w", err))return@@ -53,13 +53,13 @@ func (c *invitationController) InviteUser(ctx *gin.Context) {return}- memberCount, err := repositories.OrganizationRepository.CountMembers(tx, organizationId)+ memberCount, err := transactional.OrganizationRepository.CountMembers(tx, organizationId)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to count members: %w", err))return}- invitations, err := repositories.InvitationRepository.FindByOrganization(tx, organizationId)+ invitations, err := transactional.InvitationRepository.FindByOrganization(tx, organizationId)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to count invitations: %w", err))return@@ -83,20 +83,20 @@ func (c *invitationController) InviteUser(ctx *gin.Context) {}}- inviter, err := repositories.UserRepository.FindById(tx, userId)+ inviter, err := transactional.UserRepository.FindById(tx, userId)if err != nil || inviter == nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to get inviter info: %w", err))return}- org, err := repositories.OrganizationRepository.FindById(tx, organizationId)+ org, err := transactional.OrganizationRepository.FindById(tx, organizationId)if err != nil || org == nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to get organization info: %w", err))return}expiresAt := time.Now().AddDate(0, 0, invitationExpiryDays)- invitation, err := repositories.InvitationRepository.Create(tx, organizationId, request.Email, request.Role, userId, expiresAt)+ invitation, err := transactional.InvitationRepository.Create(tx, organizationId, request.Email, request.Role, userId, expiresAt)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to create invitation: %w", err))return@@ -115,7 +115,7 @@ func (c *invitationController) ListInvitations(ctx *gin.Context) {organizationId := middleware.GetOrganizationId(ctx)invitations, err := db.ExecuteTransaction(func(tx *sql.Tx) ([]*models.InvitationWithInviter, error) {- return repositories.InvitationRepository.FindByOrganization(tx, organizationId)+ return transactional.InvitationRepository.FindByOrganization(tx, organizationId)})if err != nil {@@ -136,7 +136,7 @@ func (c *invitationController) RevokeInvitation(ctx *gin.Context) {return}- invitation, err := repositories.InvitationRepository.FindById(tx, invitationId)+ invitation, err := transactional.InvitationRepository.FindById(tx, invitationId)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to find invitation: %w", err))return@@ -150,7 +150,7 @@ func (c *invitationController) RevokeInvitation(ctx *gin.Context) {return}- err = repositories.InvitationRepository.Delete(tx, invitationId)+ err = transactional.InvitationRepository.Delete(tx, invitationId)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to revoke invitation: %w", err))return@@ -170,7 +170,7 @@ func (c *invitationController) GetInvitationInfo(ctx *gin.Context) {}data, err := db.ExecuteTransaction(func(tx *sql.Tx) (*invitationInfo, error) {- invitation, err := repositories.InvitationRepository.FindByToken(tx, token)+ invitation, err := transactional.InvitationRepository.FindByToken(tx, token)if err != nil {return nil, err}@@ -178,17 +178,17 @@ func (c *invitationController) GetInvitationInfo(ctx *gin.Context) {return nil, nil}- org, err := repositories.OrganizationRepository.FindById(tx, invitation.OrganizationId)+ org, err := transactional.OrganizationRepository.FindById(tx, invitation.OrganizationId)if err != nil {return nil, err}- inviter, err := repositories.UserRepository.FindById(tx, invitation.InvitedBy)+ inviter, err := transactional.UserRepository.FindById(tx, invitation.InvitedBy)if err != nil {return nil, err}- userExists, err := repositories.UserRepository.EmailExists(tx, invitation.Email)+ userExists, err := transactional.UserRepository.EmailExists(tx, invitation.Email)if err != nil {return nil, err}@@ -240,7 +240,7 @@ func (c *invitationController) AcceptInvitation(ctx *gin.Context) {return}- invitation, err := repositories.InvitationRepository.FindByToken(tx, token)+ invitation, err := transactional.InvitationRepository.FindByToken(tx, token)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to load invitation: %w", err))return@@ -260,7 +260,7 @@ func (c *invitationController) AcceptInvitation(ctx *gin.Context) {return}- existingUser, err := repositories.UserRepository.FindByEmail(tx, invitation.Email)+ existingUser, err := transactional.UserRepository.FindByEmail(tx, invitation.Email)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to check user: %w", err))return@@ -276,13 +276,13 @@ func (c *invitationController) AcceptInvitation(ctx *gin.Context) {return}- user, err := repositories.UserRepository.Create(tx, invitation.Email, request.Name, hashedPassword)+ user, err := transactional.UserRepository.Create(tx, invitation.Email, request.Name, hashedPassword)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to create user: %w", err))return}- _, err = repositories.OrganizationRepository.AddUser(tx, invitation.OrganizationId, user.Id, invitation.Role)+ _, err = transactional.OrganizationRepository.AddUser(tx, invitation.OrganizationId, user.Id, invitation.Role)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to add user to organization: %w", err))return@@ -292,7 +292,7 @@ func (c *invitationController) AcceptInvitation(ctx *gin.Context) {invitation.AcceptedAt = &nowinvitation.Status = "accepted"- err = repositories.InvitationRepository.Update(tx, invitation)+ err = transactional.InvitationRepository.Update(tx, invitation)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to update invitation: %w", err))return@@ -304,7 +304,7 @@ func (c *invitationController) AcceptInvitation(ctx *gin.Context) {return}- projects, err := repositories.ProjectRepository.FindAllWithBackendUrlByUserId(tx, user.Id)+ projects, err := transactional.ProjectRepository.FindAllWithBackendUrlByUserId(tx, user.Id)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to load projects: %w", err))return@@ -323,7 +323,7 @@ func (c *invitationController) AcceptExistingUser(ctx *gin.Context) {userId := middleware.GetUserId(ctx)userEmail := middleware.GetUserEmail(ctx)- invitation, err := repositories.InvitationRepository.FindByToken(tx, token)+ invitation, err := transactional.InvitationRepository.FindByToken(tx, token)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to load invitation: %w", err))return@@ -348,7 +348,7 @@ func (c *invitationController) AcceptExistingUser(ctx *gin.Context) {return}- isMember, err := repositories.OrganizationRepository.IsUserMember(tx, invitation.OrganizationId, userId)+ isMember, err := transactional.OrganizationRepository.IsUserMember(tx, invitation.OrganizationId, userId)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to check membership: %w", err))return@@ -358,7 +358,7 @@ func (c *invitationController) AcceptExistingUser(ctx *gin.Context) {return}- _, err = repositories.OrganizationRepository.AddUser(tx, invitation.OrganizationId, userId, invitation.Role)+ _, err = transactional.OrganizationRepository.AddUser(tx, invitation.OrganizationId, userId, invitation.Role)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to add you to organization: %w", err))return@@ -368,13 +368,13 @@ func (c *invitationController) AcceptExistingUser(ctx *gin.Context) {invitation.AcceptedAt = &nowinvitation.Status = "accepted"- err = repositories.InvitationRepository.Update(tx, invitation)+ err = transactional.InvitationRepository.Update(tx, invitation)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to update invitation: %w", err))return}- projects, err := repositories.ProjectRepository.FindAllWithBackendUrlByUserId(tx, userId)+ projects, err := transactional.ProjectRepository.FindAllWithBackendUrlByUserId(tx, userId)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to load projects: %w", err))returndiff --git a/backend/app/controllers/log.controller.go b/backend/app/controllers/log.controller.goindex 31297c04..42bc6dea 100644--- a/backend/app/controllers/log.controller.go+++ b/backend/app/controllers/log.controller.go@@ -12,7 +12,7 @@ import ("github.com/tracewayapp/traceway/backend/app/middleware""github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry")type logController struct{}@@ -81,19 +81,19 @@ func (l logController) List(c *gin.Context) {}}- attrFilters := make([]repositories.LogAttributeFilter, 0, len(request.AttributeFilters))+ attrFilters := make([]telemetry.LogAttributeFilter, 0, len(request.AttributeFilters))for _, f := range request.AttributeFilters {if f.Key == "" || f.Scope == "" {continue}- attrFilters = append(attrFilters, repositories.LogAttributeFilter{+ attrFilters = append(attrFilters, telemetry.LogAttributeFilter{Scope: f.Scope,Key: f.Key,Value: f.Value,})}- params := repositories.LogSearchParams{+ params := telemetry.LogSearchParams{ProjectId: projectId,FromDate: request.FromDate,ToDate: request.ToDate,@@ -137,7 +137,7 @@ func (l logController) List(c *gin.Context) {}span := traceway.StartSpan(c, "loading logs")- records, total, err := repositories.LogRecordRepository.Search(c, params)+ records, total, err := telemetry.LogRecordRepository.Search(c, params)span.End()if err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading logs: %w", err))@@ -163,15 +163,15 @@ func (l logController) resolveDistributedTraceIds(ctx context.Context, dtid uuidrecordedAtHint = &recordedAt}- endpoints, err := repositories.EndpointRepository.FindByDistributedTraceId(ctx, dtid, projectIds, recordedAtHint)+ endpoints, err := telemetry.EndpointRepository.FindByDistributedTraceId(ctx, dtid, projectIds, recordedAtHint)if err != nil {return nil, err}- tasks, err := repositories.TaskRepository.FindByDistributedTraceId(ctx, dtid, projectIds, recordedAtHint)+ tasks, err := telemetry.TaskRepository.FindByDistributedTraceId(ctx, dtid, projectIds, recordedAtHint)if err != nil {return nil, err}- aiTraces, err := repositories.AiTraceRepository.FindByDistributedTraceId(ctx, dtid, projectIds, recordedAtHint)+ aiTraces, err := telemetry.AiTraceRepository.FindByDistributedTraceId(ctx, dtid, projectIds, recordedAtHint)if err != nil {return nil, err}diff --git a/backend/app/controllers/member.controller.go b/backend/app/controllers/member.controller.goindex e0de87f9..4bfd2391 100644--- a/backend/app/controllers/member.controller.go+++ b/backend/app/controllers/member.controller.go@@ -4,7 +4,7 @@ import ("github.com/tracewayapp/traceway/backend/app/db""github.com/tracewayapp/traceway/backend/app/middleware""github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional""net/http""strconv"@@ -32,7 +32,7 @@ func (c *memberController) UpdateRole(ctx *gin.Context) {return}- targetRole, err := repositories.OrganizationRepository.GetUserRole(tx, organizationId, targetUserId)+ targetRole, err := transactional.OrganizationRepository.GetUserRole(tx, organizationId, targetUserId)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to get user role: %w", err))return@@ -57,7 +57,7 @@ func (c *memberController) UpdateRole(ctx *gin.Context) {return}- err = repositories.OrganizationRepository.UpdateUserRole(tx, organizationId, targetUserId, request.Role)+ err = transactional.OrganizationRepository.UpdateUserRole(tx, organizationId, targetUserId, request.Role)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to update role: %w", err))return@@ -82,7 +82,7 @@ func (c *memberController) RemoveMember(ctx *gin.Context) {return}- targetRole, err := repositories.OrganizationRepository.GetUserRole(tx, organizationId, targetUserId)+ targetRole, err := transactional.OrganizationRepository.GetUserRole(tx, organizationId, targetUserId)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to get user role: %w", err))return@@ -97,7 +97,7 @@ func (c *memberController) RemoveMember(ctx *gin.Context) {return}- err = repositories.OrganizationRepository.RemoveUser(tx, organizationId, targetUserId)+ err = transactional.OrganizationRepository.RemoveUser(tx, organizationId, targetUserId)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to remove member: %w", err))returndiff --git a/backend/app/controllers/metric_query.controller.go b/backend/app/controllers/metric_query.controller.goindex b6fb6953..88c222aa 100644--- a/backend/app/controllers/metric_query.controller.go+++ b/backend/app/controllers/metric_query.controller.go@@ -9,7 +9,8 @@ import ("github.com/tracewayapp/traceway/backend/app/db""github.com/tracewayapp/traceway/backend/app/middleware""github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional""github.com/gin-gonic/gin"traceway "go.tracewayapp.com"@@ -60,7 +61,7 @@ func (c *metricQueryController) Query(ctx *gin.Context) {unitMap := make(map[string]string)registry, regErr := db.ExecuteTransaction(func(tx *sql.Tx) ([]*models.MetricRegistry, error) {- return repositories.MetricRegistryRepository.FindByProject(tx, projectId)+ return transactional.MetricRegistryRepository.FindByProject(tx, projectId)})if regErr != nil {traceway.CaptureException(fmt.Errorf("failed to load metric registry for query: %w", regErr))@@ -86,7 +87,7 @@ func (c *metricQueryController) Query(ctx *gin.Context) {spanName += fmt.Sprintf(" filters=%d", len(q.TagFilters))}span := traceway.StartSpan(ctx, spanName)- series, err := repositories.MetricPointRepository.QueryTimeSeries(+ series, err := telemetry.MetricPointRepository.QueryTimeSeries(ctx, projectId, q.Name, req.From, req.To,req.IntervalMinutes, agg, q.TagFilters, q.GroupBy,)@@ -137,7 +138,7 @@ func (c *metricQueryController) Discover(ctx *gin.Context) {}span := traceway.StartSpan(ctx, "discover metrics")- discovered, err := repositories.MetricPointRepository.DiscoverMetrics(ctx, projectId, from, to)+ discovered, err := telemetry.MetricPointRepository.DiscoverMetrics(ctx, projectId, from, to)span.End()if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to discover metrics: %w", err))@@ -145,7 +146,7 @@ func (c *metricQueryController) Discover(ctx *gin.Context) {}registry, regErr := db.ExecuteTransaction(func(tx *sql.Tx) ([]*models.MetricRegistry, error) {- return repositories.MetricRegistryRepository.FindByProject(tx, projectId)+ return transactional.MetricRegistryRepository.FindByProject(tx, projectId)})if regErr != nil {@@ -185,7 +186,7 @@ func (c *metricQueryController) DiscoverTags(ctx *gin.Context) {to := time.Now()span := traceway.StartSpan(ctx, fmt.Sprintf("discover tag values: %s.%s", name, key))- values, err := repositories.MetricPointRepository.DiscoverTagValues(ctx, projectId, name, key, from, to)+ values, err := telemetry.MetricPointRepository.DiscoverTagValues(ctx, projectId, name, key, from, to)span.End()if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to discover tag values: %w", err))@@ -219,7 +220,7 @@ func (c *metricQueryController) UpdateRegistry(ctx *gin.Context) {}updated, err := db.ExecuteTransaction(func(tx *sql.Tx) (*models.MetricRegistry, error) {- entry, err := repositories.MetricRegistryRepository.FindByProjectAndName(tx, projectId, req.Name)+ entry, err := transactional.MetricRegistryRepository.FindByProjectAndName(tx, projectId, req.Name)if err != nil {return nil, err}@@ -233,7 +234,7 @@ func (c *metricQueryController) UpdateRegistry(ctx *gin.Context) {entry.Unit = req.Unit}entry.Description = req.Description- if err := repositories.MetricRegistryRepository.Update(tx, entry); err != nil {+ if err := transactional.MetricRegistryRepository.Update(tx, entry); err != nil {return nil, err}return entry, nildiff --git a/backend/app/controllers/metric_record.controller.go b/backend/app/controllers/metric_record.controller.goindex d2bd6a05..0f19b76c 100644--- a/backend/app/controllers/metric_record.controller.go+++ b/backend/app/controllers/metric_record.controller.go@@ -3,7 +3,7 @@ package controllersimport ("github.com/tracewayapp/traceway/backend/app/middleware""github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry""net/http""time"@@ -27,13 +27,13 @@ func (e metricRecordController) FindHomepageStats(c *gin.Context) {// requestsspan := traceway.StartSpan(c, "loading requests stats")- requestsNow, err := repositories.EndpointRepository.CountBetween(c, projectId, oneDayAgo, now)+ requestsNow, err := telemetry.EndpointRepository.CountBetween(c, projectId, oneDayAgo, now)if err != nil {span.End()c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading requestsNow: %w", err))return}- requestsPrev, err := repositories.EndpointRepository.CountBetween(c, projectId, twoDaysAgo, oneDayAgo)+ requestsPrev, err := telemetry.EndpointRepository.CountBetween(c, projectId, twoDaysAgo, oneDayAgo)span.End()if err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading requestsPrev: %w", err))@@ -42,13 +42,13 @@ func (e metricRecordController) FindHomepageStats(c *gin.Context) {// exceptionsspan = traceway.StartSpan(c, "loading exceptions stats")- exceptionsNow, err := repositories.ExceptionStackTraceRepository.CountBetween(c, projectId, oneDayAgo, now)+ exceptionsNow, err := telemetry.ExceptionStackTraceRepository.CountBetween(c, projectId, oneDayAgo, now)if err != nil {span.End()c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading exceptionsNow: %w", err))return}- exceptionsPrev, err := repositories.ExceptionStackTraceRepository.CountBetween(c, projectId, twoDaysAgo, oneDayAgo)+ exceptionsPrev, err := telemetry.ExceptionStackTraceRepository.CountBetween(c, projectId, twoDaysAgo, oneDayAgo)span.End()if err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading exceptionsPrev: %w", err))@@ -57,13 +57,13 @@ func (e metricRecordController) FindHomepageStats(c *gin.Context) {// ram usage last 24h vs previous 24hspan = traceway.StartSpan(c, "loading ram usage")- ramNow, err := repositories.MetricPointRepository.GetAverageBetween(c, projectId, models.MetricNameMemoryUsage, oneDayAgo, now)+ ramNow, err := telemetry.MetricPointRepository.GetAverageBetween(c, projectId, models.MetricNameMemoryUsage, oneDayAgo, now)if err != nil {span.End()c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading ramNow: %w", err))return}- ramPrev, err := repositories.MetricPointRepository.GetAverageBetween(c, projectId, models.MetricNameMemoryUsage, twoDaysAgo, oneDayAgo)+ ramPrev, err := telemetry.MetricPointRepository.GetAverageBetween(c, projectId, models.MetricNameMemoryUsage, twoDaysAgo, oneDayAgo)span.End()if err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading ramPrev: %w", err))@@ -72,13 +72,13 @@ func (e metricRecordController) FindHomepageStats(c *gin.Context) {// memory usage last 24h vs previous 24hspan = traceway.StartSpan(c, "loading cpu usage")- cpuNow, err := repositories.MetricPointRepository.GetAverageBetween(c, projectId, models.MetricNameCpuUsage, oneDayAgo, now)+ cpuNow, err := telemetry.MetricPointRepository.GetAverageBetween(c, projectId, models.MetricNameCpuUsage, oneDayAgo, now)if err != nil {span.End()c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading cpuNow: %w", err))return}- cpuPrev, err := repositories.MetricPointRepository.GetAverageBetween(c, projectId, models.MetricNameCpuUsage, twoDaysAgo, oneDayAgo)+ cpuPrev, err := telemetry.MetricPointRepository.GetAverageBetween(c, projectId, models.MetricNameCpuUsage, twoDaysAgo, oneDayAgo)span.End()if err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading cpuPrev: %w", err))diff --git a/backend/app/controllers/metrics.controller.go b/backend/app/controllers/metrics.controller.goindex 1c35d25d..a20fa786 100644--- a/backend/app/controllers/metrics.controller.go+++ b/backend/app/controllers/metrics.controller.go@@ -2,7 +2,7 @@ package controllersimport ("github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry""net/http""time"@@ -51,7 +51,7 @@ func (m metricsController) GetApplicationMetrics(c *gin.Context) {intervalMinutes := calculateIntervalMinutes(duration)// Get available servers in the time range- availableServers, err := repositories.MetricPointRepository.GetDistinctServers(c, projectId, start, end)+ availableServers, err := telemetry.MetricPointRepository.GetDistinctServers(c, projectId, start, end)if err != nil {availableServers = []string{}}@@ -63,43 +63,43 @@ func (m metricsController) GetApplicationMetrics(c *gin.Context) {// 1. Go Routinesspan := traceway.StartSpan(c, "loading go routines")- goRoutinesPerServer, err := repositories.MetricPointRepository.GetAverageByIntervalPerServer(c, projectId, models.MetricNameGoRoutines, start, end, intervalMinutes, emptyServers)+ goRoutinesPerServer, err := telemetry.MetricPointRepository.GetAverageByIntervalPerServer(c, projectId, models.MetricNameGoRoutines, start, end, intervalMinutes, emptyServers)if err != nil {span.End()c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading goRoutinesPerServer: %w", err))return}- goRoutinesPrev, _ := repositories.MetricPointRepository.GetAverageBetween(c, projectId, models.MetricNameGoRoutines, prevStart, prevEnd)+ goRoutinesPrev, _ := telemetry.MetricPointRepository.GetAverageBetween(c, projectId, models.MetricNameGoRoutines, prevStart, prevEnd)span.End()metrics = append(metrics, buildMetricWithServers("go_routines", "Go Routines", "", goRoutinesPerServer, goRoutinesPrev, "go_routines"))// 2. Heap Objectsspan = traceway.StartSpan(c, "loading heap objects")- heapObjectsPerServer, err := repositories.MetricPointRepository.GetAverageByIntervalPerServer(c, projectId, models.MetricNameHeapObjects, start, end, intervalMinutes, emptyServers)+ heapObjectsPerServer, err := telemetry.MetricPointRepository.GetAverageByIntervalPerServer(c, projectId, models.MetricNameHeapObjects, start, end, intervalMinutes, emptyServers)if err != nil {span.End()c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading heapObjectsPerServer: %w", err))return}- heapObjectsPrev, _ := repositories.MetricPointRepository.GetAverageBetween(c, projectId, models.MetricNameHeapObjects, prevStart, prevEnd)+ heapObjectsPrev, _ := telemetry.MetricPointRepository.GetAverageBetween(c, projectId, models.MetricNameHeapObjects, prevStart, prevEnd)span.End()metrics = append(metrics, buildMetricWithServers("heap_objects", "Heap Objects", "", heapObjectsPerServer, heapObjectsPrev, "heap_objects"))// 3. GC Cycles (Num GC)span = traceway.StartSpan(c, "loading gc cycles")- numGCPerServer, err := repositories.MetricPointRepository.GetAverageByIntervalPerServer(c, projectId, models.MetricNameNumGC, start, end, intervalMinutes, emptyServers)+ numGCPerServer, err := telemetry.MetricPointRepository.GetAverageByIntervalPerServer(c, projectId, models.MetricNameNumGC, start, end, intervalMinutes, emptyServers)if err != nil {span.End()c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading numGCPerServer: %w", err))return}- numGCPrev, _ := repositories.MetricPointRepository.GetAverageBetween(c, projectId, models.MetricNameNumGC, prevStart, prevEnd)+ numGCPrev, _ := telemetry.MetricPointRepository.GetAverageBetween(c, projectId, models.MetricNameNumGC, prevStart, prevEnd)span.End()metrics = append(metrics, buildMetricWithServers("num_gc", "GC Cycles", "", numGCPerServer, numGCPrev, "num_gc"))// 4. GC Pause Total (convert from nanoseconds to milliseconds)span = traceway.StartSpan(c, "loading gc pause")- gcPausePerServer, err := repositories.MetricPointRepository.GetAverageByIntervalPerServer(c, projectId, models.MetricNameGCPauseTotal, start, end, intervalMinutes, emptyServers)+ gcPausePerServer, err := telemetry.MetricPointRepository.GetAverageByIntervalPerServer(c, projectId, models.MetricNameGCPauseTotal, start, end, intervalMinutes, emptyServers)if err != nil {span.End()c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading gcPausePerServer: %w", err))@@ -111,7 +111,7 @@ func (m metricsController) GetApplicationMetrics(c *gin.Context) {gcPausePerServer[serverName][i].Value = points[i].Value / 1_000_000}}- gcPausePrevRaw, _ := repositories.MetricPointRepository.GetAverageBetween(c, projectId, models.MetricNameGCPauseTotal, prevStart, prevEnd)+ gcPausePrevRaw, _ := telemetry.MetricPointRepository.GetAverageBetween(c, projectId, models.MetricNameGCPauseTotal, prevStart, prevEnd)span.End()gcPausePrev := gcPausePrevRaw / 1_000_000metrics = append(metrics, buildMetricWithServers("gc_pause", "GC Pause", "ms", gcPausePerServer, gcPausePrev, "gc_pause"))@@ -146,54 +146,54 @@ func (m metricsController) GetStatsMetrics(c *gin.Context) {// 1. Requests countspan := traceway.StartSpan(c, "loading requests trend")- requestsTrend, err := repositories.EndpointRepository.CountByInterval(c, projectId, start, end, intervalMinutes)+ requestsTrend, err := telemetry.EndpointRepository.CountByInterval(c, projectId, start, end, intervalMinutes)if err != nil {span.End()c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading requestsTrend: %w", err))return}- requestsCurrent, _ := repositories.EndpointRepository.CountBetween(c, projectId, start, end)- requestsPrev, _ := repositories.EndpointRepository.CountBetween(c, projectId, prevStart, prevEnd)+ requestsCurrent, _ := telemetry.EndpointRepository.CountBetween(c, projectId, start, end)+ requestsPrev, _ := telemetry.EndpointRepository.CountBetween(c, projectId, prevStart, prevEnd)span.End()metrics = append(metrics, buildMetric("requests", "Requests", float64(requestsCurrent), "count", requestsTrend, float64(requestsPrev), "requests"))// 2. Exceptions countspan = traceway.StartSpan(c, "loading exceptions trend")- exceptionsTrend, err := repositories.ExceptionStackTraceRepository.CountByInterval(c, projectId, start, end, intervalMinutes)+ exceptionsTrend, err := telemetry.ExceptionStackTraceRepository.CountByInterval(c, projectId, start, end, intervalMinutes)if err != nil {span.End()c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading exceptionsTrend: %w", err))return}- exceptionsCurrent, _ := repositories.ExceptionStackTraceRepository.CountBetween(c, projectId, start, end)- exceptionsPrev, _ := repositories.ExceptionStackTraceRepository.CountBetween(c, projectId, prevStart, prevEnd)+ exceptionsCurrent, _ := telemetry.ExceptionStackTraceRepository.CountBetween(c, projectId, start, end)+ exceptionsPrev, _ := telemetry.ExceptionStackTraceRepository.CountBetween(c, projectId, prevStart, prevEnd)span.End()metrics = append(metrics, buildMetric("exceptions", "Exceptions", float64(exceptionsCurrent), "count", exceptionsTrend, float64(exceptionsPrev), "exceptions"))// 3. Average Response Timespan = traceway.StartSpan(c, "loading avg response time")- avgDurationTrend, err := repositories.EndpointRepository.AvgDurationByInterval(c, projectId, start, end, intervalMinutes)+ avgDurationTrend, err := telemetry.EndpointRepository.AvgDurationByInterval(c, projectId, start, end, intervalMinutes)if err != nil {span.End()c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading avgDurationTrend: %w", err))return}avgDurationCurrent := getLastValue(avgDurationTrend)- avgDurationPrevTrend, _ := repositories.EndpointRepository.AvgDurationByInterval(c, projectId, prevStart, prevEnd, intervalMinutes)+ avgDurationPrevTrend, _ := telemetry.EndpointRepository.AvgDurationByInterval(c, projectId, prevStart, prevEnd, intervalMinutes)avgDurationPrev := getAverageValue(avgDurationPrevTrend)span.End()metrics = append(metrics, buildMetric("avg_response_time", "Avg Response Time", avgDurationCurrent, "ms", avgDurationTrend, avgDurationPrev, "response_time"))// 4. Error Ratespan = traceway.StartSpan(c, "loading error rate")- errorRateTrend, err := repositories.EndpointRepository.ErrorRateByInterval(c, projectId, start, end, intervalMinutes)+ errorRateTrend, err := telemetry.EndpointRepository.ErrorRateByInterval(c, projectId, start, end, intervalMinutes)if err != nil {span.End()c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading errorRateTrend: %w", err))return}errorRateCurrent := getLastValue(errorRateTrend)- errorRatePrevTrend, _ := repositories.EndpointRepository.ErrorRateByInterval(c, projectId, prevStart, prevEnd, intervalMinutes)+ errorRatePrevTrend, _ := telemetry.EndpointRepository.ErrorRateByInterval(c, projectId, prevStart, prevEnd, intervalMinutes)errorRatePrev := getAverageValue(errorRatePrevTrend)span.End()metrics = append(metrics, buildMetric("error_rate", "Error Rate", errorRateCurrent, "%", errorRateTrend, errorRatePrev, "error_rate"))@@ -224,7 +224,7 @@ func (m metricsController) GetServerMetrics(c *gin.Context) {intervalMinutes := calculateIntervalMinutes(duration)// Get available servers in the time range- availableServers, err := repositories.MetricPointRepository.GetDistinctServers(c, projectId, start, end)+ availableServers, err := telemetry.MetricPointRepository.GetDistinctServers(c, projectId, start, end)if err != nil {availableServers = []string{}}@@ -236,37 +236,37 @@ func (m metricsController) GetServerMetrics(c *gin.Context) {// 1. CPU Usagespan := traceway.StartSpan(c, "loading cpu usage")- cpuPerServer, err := repositories.MetricPointRepository.GetAverageByIntervalPerServer(c, projectId, models.MetricNameCpuUsage, start, end, intervalMinutes, emptyServers)+ cpuPerServer, err := telemetry.MetricPointRepository.GetAverageByIntervalPerServer(c, projectId, models.MetricNameCpuUsage, start, end, intervalMinutes, emptyServers)if err != nil {span.End()c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading cpuPerServer: %w", err))return}- cpuPrev, _ := repositories.MetricPointRepository.GetAverageBetween(c, projectId, models.MetricNameCpuUsage, prevStart, prevEnd)+ cpuPrev, _ := telemetry.MetricPointRepository.GetAverageBetween(c, projectId, models.MetricNameCpuUsage, prevStart, prevEnd)span.End()metrics = append(metrics, buildMetricWithServers("cpu_usage", "CPU Usage", "%", cpuPerServer, cpuPrev, "cpu"))// 2. Memory Usage (MB)span = traceway.StartSpan(c, "loading memory usage")- memPerServer, err := repositories.MetricPointRepository.GetAverageByIntervalPerServer(c, projectId, models.MetricNameMemoryUsage, start, end, intervalMinutes, emptyServers)+ memPerServer, err := telemetry.MetricPointRepository.GetAverageByIntervalPerServer(c, projectId, models.MetricNameMemoryUsage, start, end, intervalMinutes, emptyServers)if err != nil {span.End()c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading memPerServer: %w", err))return}- memPrev, _ := repositories.MetricPointRepository.GetAverageBetween(c, projectId, models.MetricNameMemoryUsage, prevStart, prevEnd)+ memPrev, _ := telemetry.MetricPointRepository.GetAverageBetween(c, projectId, models.MetricNameMemoryUsage, prevStart, prevEnd)span.End()metrics = append(metrics, buildMetricWithServers("memory_usage", "Memory Usage", "MB", memPerServer, memPrev, "memory"))// 3. Total System Memory (MB)span = traceway.StartSpan(c, "loading total memory")- memTotalPerServer, err := repositories.MetricPointRepository.GetAverageByIntervalPerServer(c, projectId, models.MetricNameMemoryTotal, start, end, intervalMinutes, emptyServers)+ memTotalPerServer, err := telemetry.MetricPointRepository.GetAverageByIntervalPerServer(c, projectId, models.MetricNameMemoryTotal, start, end, intervalMinutes, emptyServers)if err != nil {span.End()c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading memTotalPerServer: %w", err))return}- memTotalPrev, _ := repositories.MetricPointRepository.GetAverageBetween(c, projectId, models.MetricNameMemoryTotal, prevStart, prevEnd)+ memTotalPrev, _ := telemetry.MetricPointRepository.GetAverageBetween(c, projectId, models.MetricNameMemoryTotal, prevStart, prevEnd)span.End()metrics = append(metrics, buildMetricWithServers("memory_total", "Total Memory", "MB", memTotalPerServer, memTotalPrev, "memory_total"))diff --git a/backend/app/controllers/notification_channel.controller.go b/backend/app/controllers/notification_channel.controller.goindex 38e92961..be1f8d6e 100644--- a/backend/app/controllers/notification_channel.controller.go+++ b/backend/app/controllers/notification_channel.controller.go@@ -13,7 +13,7 @@ import ("github.com/tracewayapp/traceway/backend/app/middleware""github.com/tracewayapp/traceway/backend/app/models""github.com/tracewayapp/traceway/backend/app/notifications"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional"traceway "go.tracewayapp.com")@@ -27,7 +27,7 @@ func (ctrl *notificationChannelController) List(ctx *gin.Context) {}tx := db.GetTx(ctx)- channels, err := repositories.NotificationChannelRepository.FindByProject(tx, projectId)+ channels, err := transactional.NotificationChannelRepository.FindByProject(tx, projectId)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to list notification channels: %w", err))return@@ -102,7 +102,7 @@ func (ctrl *notificationChannelController) Create(ctx *gin.Context) {UpdatedAt: now,}- id, err := repositories.NotificationChannelRepository.Create(tx, channel)+ id, err := transactional.NotificationChannelRepository.Create(tx, channel)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to create notification channel: %w", err))return@@ -157,7 +157,7 @@ func (ctrl *notificationChannelController) Update(ctx *gin.Context) {}tx := db.GetTx(ctx)- existing, err := repositories.NotificationChannelRepository.FindById(tx, id)+ existing, err := transactional.NotificationChannelRepository.FindById(tx, id)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to find notification channel: %w", err))return@@ -172,7 +172,7 @@ func (ctrl *notificationChannelController) Update(ctx *gin.Context) {existing.Config = req.Configexisting.UpdatedAt = time.Now().UTC()- if err := repositories.NotificationChannelRepository.Update(tx, existing); err != nil {+ if err := transactional.NotificationChannelRepository.Update(tx, existing); err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to update notification channel: %w", err))return}@@ -195,7 +195,7 @@ func (ctrl *notificationChannelController) Delete(ctx *gin.Context) {}tx := db.GetTx(ctx)- existing, err := repositories.NotificationChannelRepository.FindById(tx, id)+ existing, err := transactional.NotificationChannelRepository.FindById(tx, id)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to delete notification channel: %w", err))return@@ -205,7 +205,7 @@ func (ctrl *notificationChannelController) Delete(ctx *gin.Context) {return}- if err := repositories.NotificationChannelRepository.Delete(tx, id); err != nil {+ if err := transactional.NotificationChannelRepository.Delete(tx, id); err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to delete notification channel: %w", err))return}@@ -228,7 +228,7 @@ func (ctrl *notificationChannelController) Test(ctx *gin.Context) {}channel, err := db.ExecuteTransaction(func(tx *sql.Tx) (*models.NotificationChannel, error) {- return repositories.NotificationChannelRepository.FindById(tx, id)+ return transactional.NotificationChannelRepository.FindById(tx, id)})if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to find notification channel: %w", err))diff --git a/backend/app/controllers/notification_history.controller.go b/backend/app/controllers/notification_history.controller.goindex 801ef165..60cb7d88 100644--- a/backend/app/controllers/notification_history.controller.go+++ b/backend/app/controllers/notification_history.controller.go@@ -7,7 +7,7 @@ import ("github.com/gin-gonic/gin""github.com/tracewayapp/traceway/backend/app/middleware""github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry"traceway "go.tracewayapp.com")@@ -54,7 +54,7 @@ func (ctrl *notificationHistoryController) List(ctx *gin.Context) {toTime = &t}- items, total, err := repositories.FiredNotificationRepository.FindByProject(ctx.Request.Context(), projectId, page, pageSize, request.Search, fromTime, toTime)+ items, total, err := telemetry.FiredNotificationRepository.FindByProject(ctx.Request.Context(), projectId, page, pageSize, request.Search, fromTime, toTime)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to list notification history: %w", err))returndiff --git a/backend/app/controllers/notification_rule.controller.go b/backend/app/controllers/notification_rule.controller.goindex df83530a..7060e3f2 100644--- a/backend/app/controllers/notification_rule.controller.go+++ b/backend/app/controllers/notification_rule.controller.go@@ -12,7 +12,7 @@ import ("github.com/tracewayapp/traceway/backend/app/middleware""github.com/tracewayapp/traceway/backend/app/models""github.com/tracewayapp/traceway/backend/app/notifications"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional"traceway "go.tracewayapp.com")@@ -46,7 +46,7 @@ func (ctrl *notificationRuleController) List(ctx *gin.Context) {}tx := db.GetTx(ctx)- rules, err := repositories.NotificationRuleRepository.FindByProjectWithChannel(tx, projectId)+ rules, err := transactional.NotificationRuleRepository.FindByProjectWithChannel(tx, projectId)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to list notification rules: %w", err))return@@ -107,7 +107,7 @@ func (ctrl *notificationRuleController) Create(ctx *gin.Context) {tx := db.GetTx(ctx)- channel, err := repositories.NotificationChannelRepository.FindById(tx, req.ChannelId)+ channel, err := transactional.NotificationChannelRepository.FindById(tx, req.ChannelId)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to find notification channel: %w", err))return@@ -142,7 +142,7 @@ func (ctrl *notificationRuleController) Create(ctx *gin.Context) {UpdatedAt: now,}- id, err := repositories.NotificationRuleRepository.Create(tx, rule)+ id, err := transactional.NotificationRuleRepository.Create(tx, rule)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to create notification rule: %w", err))return@@ -192,7 +192,7 @@ func (ctrl *notificationRuleController) Update(ctx *gin.Context) {tx := db.GetTx(ctx)- existing, err := repositories.NotificationRuleRepository.FindById(tx, id)+ existing, err := transactional.NotificationRuleRepository.FindById(tx, id)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to find notification rule: %w", err))return@@ -202,7 +202,7 @@ func (ctrl *notificationRuleController) Update(ctx *gin.Context) {return}- channel, err := repositories.NotificationChannelRepository.FindById(tx, req.ChannelId)+ channel, err := transactional.NotificationChannelRepository.FindById(tx, req.ChannelId)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to find notification channel: %w", err))return@@ -225,7 +225,7 @@ func (ctrl *notificationRuleController) Update(ctx *gin.Context) {existing.Severity = req.Severityexisting.UpdatedAt = time.Now().UTC()- if err := repositories.NotificationRuleRepository.Update(tx, existing); err != nil {+ if err := transactional.NotificationRuleRepository.Update(tx, existing); err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to update notification rule: %w", err))return}@@ -249,7 +249,7 @@ func (ctrl *notificationRuleController) Delete(ctx *gin.Context) {}tx := db.GetTx(ctx)- existing, err := repositories.NotificationRuleRepository.FindById(tx, id)+ existing, err := transactional.NotificationRuleRepository.FindById(tx, id)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to delete notification rule: %w", err))return@@ -259,7 +259,7 @@ func (ctrl *notificationRuleController) Delete(ctx *gin.Context) {return}- if err := repositories.NotificationRuleRepository.Delete(tx, id); err != nil {+ if err := transactional.NotificationRuleRepository.Delete(tx, id); err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to delete notification rule: %w", err))return}@@ -283,7 +283,7 @@ func (ctrl *notificationRuleController) Toggle(ctx *gin.Context) {}tx := db.GetTx(ctx)- existing, err := repositories.NotificationRuleRepository.FindById(tx, id)+ existing, err := transactional.NotificationRuleRepository.FindById(tx, id)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to find notification rule: %w", err))return@@ -294,7 +294,7 @@ func (ctrl *notificationRuleController) Toggle(ctx *gin.Context) {}newEnabled := !existing.Enabled- if err := repositories.NotificationRuleRepository.UpdateEnabled(tx, id, newEnabled); err != nil {+ if err := transactional.NotificationRuleRepository.UpdateEnabled(tx, id, newEnabled); err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to toggle notification rule: %w", err))return}@@ -328,7 +328,7 @@ func (ctrl *notificationRuleController) Snooze(ctx *gin.Context) {}tx := db.GetTx(ctx)- existing, err := repositories.NotificationRuleRepository.FindById(tx, id)+ existing, err := transactional.NotificationRuleRepository.FindById(tx, id)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to find notification rule: %w", err))return@@ -344,7 +344,7 @@ func (ctrl *notificationRuleController) Snooze(ctx *gin.Context) {snoozedUntil = &t}- if err := repositories.NotificationRuleRepository.UpdateSnoozedUntil(tx, id, snoozedUntil); err != nil {+ if err := transactional.NotificationRuleRepository.UpdateSnoozedUntil(tx, id, snoozedUntil); err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to snooze notification rule: %w", err))return}diff --git a/backend/app/controllers/oauth.controller.go b/backend/app/controllers/oauth.controller.goindex f9c0c230..829a63f4 100644--- a/backend/app/controllers/oauth.controller.go+++ b/backend/app/controllers/oauth.controller.go@@ -14,7 +14,7 @@ import ("github.com/tracewayapp/traceway/backend/app/db""github.com/tracewayapp/traceway/backend/app/middleware""github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional""github.com/tracewayapp/traceway/backend/app/services""github.com/gin-gonic/gin"@@ -98,7 +98,7 @@ func (a oauthController) Callback(c *gin.Context) {mappedRole = services.OAuthService.ResolveRole(gothUser.RawData)}- memberships, err := repositories.OrganizationRepository.FindByUserIdWithRoles(tx, user.Id)+ memberships, err := transactional.OrganizationRepository.FindByUserIdWithRoles(tx, user.Id)if err != nil {c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("OAuth callback: load memberships: %w", err))return@@ -116,7 +116,7 @@ func (a oauthController) Callback(c *gin.Context) {if mappedRole != "" {role = mappedRole}- if _, err := repositories.OrganizationRepository.AddUser(tx, org.Id, user.Id, role); err != nil {+ if _, err := transactional.OrganizationRepository.AddUser(tx, org.Id, user.Id, role); err != nil {c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("OAuth callback: auto-join org: %w", err))return}@@ -127,7 +127,7 @@ func (a oauthController) Callback(c *gin.Context) {if m.Role == "owner" {continue}- if err := repositories.OrganizationRepository.UpdateUserRole(tx, m.Id, user.Id, mappedRole); err != nil {+ if err := transactional.OrganizationRepository.UpdateUserRole(tx, m.Id, user.Id, mappedRole); err != nil {c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("OAuth callback: sync mapped role: %w", err))return}@@ -151,7 +151,7 @@ func (a oauthController) Callback(c *gin.Context) {func (a oauthController) findOrCreateUser(c *gin.Context, provider string, gothUser goth.User) (*models.User, error) {tracewayTx := db.GetTx(c)- user, err := repositories.UserRepository.FindByOAuth(tracewayTx, provider, gothUser.UserID)+ user, err := transactional.UserRepository.FindByOAuth(tracewayTx, provider, gothUser.UserID)if err != nil {c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("OAuth callback: lookup by provider: %w", err))return nil, err@@ -160,14 +160,14 @@ func (a oauthController) findOrCreateUser(c *gin.Context, provider string, gothUreturn user, nil}- existing, err := repositories.UserRepository.FindByEmailIgnoreCase(tracewayTx, gothUser.Email)+ existing, err := transactional.UserRepository.FindByEmailIgnoreCase(tracewayTx, gothUser.Email)if err != nil {c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("OAuth callback: lookup by email: %w", err))return nil, err}if existing != nil {- if err := repositories.UserRepository.LinkOAuth(tracewayTx, existing.Id, provider, gothUser.UserID, gothUser.AvatarURL); err != nil {+ if err := transactional.UserRepository.LinkOAuth(tracewayTx, existing.Id, provider, gothUser.UserID, gothUser.AvatarURL); err != nil {c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("OAuth callback: link provider: %w", err))return nil, err}@@ -176,7 +176,7 @@ func (a oauthController) findOrCreateUser(c *gin.Context, provider string, gothUoidcAutoCreate := provider == "oidc" && services.OAuthService.OIDCAutoCreateEnabled()if config.Config.CloudMode != "true" && !oidcAutoCreate {- hasOrg, err := repositories.OrganizationRepository.HasOrganizations(tracewayTx)+ hasOrg, err := transactional.OrganizationRepository.HasOrganizations(tracewayTx)if err != nil {c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("OAuth callback: count orgs: %w", err))return nil, err@@ -195,7 +195,7 @@ func (a oauthController) findOrCreateUser(c *gin.Context, provider string, gothUname = gothUser.Email}- created, err := repositories.UserRepository.CreateOAuth(tracewayTx, gothUser.Email, name, provider, gothUser.UserID, gothUser.AvatarURL)+ created, err := transactional.UserRepository.CreateOAuth(tracewayTx, gothUser.Email, name, provider, gothUser.UserID, gothUser.AvatarURL)if err != nil {c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("OAuth callback: create user: %w", err))return nil, err@@ -224,7 +224,7 @@ func (a oauthController) FinishSetup(c *gin.Context) {tx := db.GetTx(c)- user, err := repositories.UserRepository.FindById(tx, userId)+ user, err := transactional.UserRepository.FindById(tx, userId)if err != nil {c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("FinishSetup: load user: %w", err))return@@ -234,7 +234,7 @@ func (a oauthController) FinishSetup(c *gin.Context) {return}- memberships, err := repositories.OrganizationRepository.FindByUserIdWithRoles(tx, user.Id)+ memberships, err := transactional.OrganizationRepository.FindByUserIdWithRoles(tx, user.Id)if err != nil {c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("FinishSetup: load memberships: %w", err))return@@ -245,7 +245,7 @@ func (a oauthController) FinishSetup(c *gin.Context) {}if config.Config.CloudMode != "true" {- hasOrg, err := repositories.OrganizationRepository.HasOrganizations(tx)+ hasOrg, err := transactional.OrganizationRepository.HasOrganizations(tx)if err != nil {c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("FinishSetup: count orgs: %w", err))return@@ -256,13 +256,13 @@ func (a oauthController) FinishSetup(c *gin.Context) {}}- org, err := repositories.OrganizationRepository.Create(tx, request.OrganizationName, request.Timezone)+ org, err := transactional.OrganizationRepository.Create(tx, request.OrganizationName, request.Timezone)if err != nil {c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("FinishSetup: create org: %w", err))return}- if _, err := repositories.OrganizationRepository.AddUser(tx, org.Id, user.Id, "owner"); err != nil {+ if _, err := transactional.OrganizationRepository.AddUser(tx, org.Id, user.Id, "owner"); err != nil {c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("FinishSetup: add user to org: %w", err))return}@@ -274,7 +274,7 @@ func (a oauthController) FinishSetup(c *gin.Context) {}}- project, err := repositories.ProjectRepository.CreateWithOrganization(tx, request.ProjectName, request.Framework, org.Id)+ project, err := transactional.ProjectRepository.CreateWithOrganization(tx, request.ProjectName, request.Framework, org.Id)if err != nil {c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("FinishSetup: create project: %w", err))return@@ -294,13 +294,13 @@ func (a oauthController) FinishSetup(c *gin.Context) {return}- projects, err := repositories.ProjectRepository.FindAllWithBackendUrlByUserId(tx, user.Id)+ projects, err := transactional.ProjectRepository.FindAllWithBackendUrlByUserId(tx, user.Id)if err != nil {c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("FinishSetup: load projects: %w", err))return}- organizations, err := repositories.OrganizationRepository.FindByUserIdWithRoles(tx, user.Id)+ organizations, err := transactional.OrganizationRepository.FindByUserIdWithRoles(tx, user.Id)if err != nil {c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("FinishSetup: load orgs: %w", err))return@@ -324,7 +324,7 @@ func (a oauthController) resolveOIDCOrg(tx *sql.Tx, rawData map[string]interfaceif claim := services.OAuthService.OIDCOrgClaim(); claim != "" {if val, ok := rawData[claim]; ok {if orgName, ok := val.(string); ok && orgName != "" {- org, err := repositories.OrganizationRepository.FindByName(tx, orgName)+ org, err := transactional.OrganizationRepository.FindByName(tx, orgName)if err != nil {return nil, err}@@ -334,7 +334,7 @@ func (a oauthController) resolveOIDCOrg(tx *sql.Tx, rawData map[string]interface}}}- return repositories.OrganizationRepository.FindFirst(tx)+ return transactional.OrganizationRepository.FindFirst(tx)}func externalToGothProvider(provider string) string {diff --git a/backend/app/controllers/oauth_authorize.controller.go b/backend/app/controllers/oauth_authorize.controller.goindex 8697725c..74737274 100644--- a/backend/app/controllers/oauth_authorize.controller.go+++ b/backend/app/controllers/oauth_authorize.controller.go@@ -11,7 +11,7 @@ import ("github.com/tracewayapp/traceway/backend/app/db""github.com/tracewayapp/traceway/backend/app/middleware""github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional""github.com/tracewayapp/traceway/backend/app/services/authserver")@@ -57,7 +57,7 @@ func (c *oauthAuthorizeController) Lookup(ctx *gin.Context) {return}- client, err := repositories.OauthClientRepository.FindById(db.DB, clientId)+ client, err := transactional.OauthClientRepository.FindById(db.DB, clientId)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("oauth client lookup: %w", err))returndiff --git a/backend/app/controllers/organization.controller.go b/backend/app/controllers/organization.controller.goindex caa729a6..c201adc9 100644--- a/backend/app/controllers/organization.controller.go+++ b/backend/app/controllers/organization.controller.go@@ -1,11 +1,11 @@package controllersimport (+ "database/sql"+ "github.com/tracewayapp/traceway/backend/app/db""github.com/tracewayapp/traceway/backend/app/middleware""github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/db"- "github.com/tracewayapp/traceway/backend/app/repositories"- "database/sql"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional""net/http""time"@@ -26,17 +26,17 @@ func (c *organizationController) GetSettings(ctx *gin.Context) {}data, err := db.ExecuteTransaction(func(tx *sql.Tx) (*settingsData, error) {- org, err := repositories.OrganizationRepository.FindById(tx, organizationId)+ org, err := transactional.OrganizationRepository.FindById(tx, organizationId)if err != nil {return nil, err}- members, err := repositories.OrganizationRepository.GetMembersWithDetails(tx, organizationId)+ members, err := transactional.OrganizationRepository.GetMembersWithDetails(tx, organizationId)if err != nil {return nil, err}- invitations, err := repositories.InvitationRepository.FindByOrganization(tx, organizationId)+ invitations, err := transactional.InvitationRepository.FindByOrganization(tx, organizationId)if err != nil {return nil, err}@@ -70,7 +70,7 @@ func (c *organizationController) GetMembers(ctx *gin.Context) {organizationId := middleware.GetOrganizationId(ctx)members, err := db.ExecuteTransaction(func(tx *sql.Tx) ([]*models.OrganizationMember, error) {- return repositories.OrganizationRepository.GetMembersWithDetails(tx, organizationId)+ return transactional.OrganizationRepository.GetMembersWithDetails(tx, organizationId)})if err != nil {@@ -101,7 +101,7 @@ func (c *organizationController) UpdateSettings(ctx *gin.Context) {return}- err = repositories.OrganizationRepository.UpdateTimezone(tx, organizationId, req.Timezone)+ err = transactional.OrganizationRepository.UpdateTimezone(tx, organizationId, req.Timezone)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to update settings: %w", err))returndiff --git a/backend/app/controllers/otelcontrollers/metric_converter.go b/backend/app/controllers/otelcontrollers/metric_converter.goindex 85764884..ec7de370 100644--- a/backend/app/controllers/otelcontrollers/metric_converter.go+++ b/backend/app/controllers/otelcontrollers/metric_converter.go@@ -2,7 +2,7 @@ package otelcontrollersimport ("github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional""github.com/google/uuid"colmetricspb "go.opentelemetry.io/proto/otlp/collector/metrics/v1"@@ -12,7 +12,7 @@ import (type convertedMetrics struct {Points []models.MetricPoint- Entries []repositories.MetricRegistrationEntry+ Entries []transactional.MetricRegistrationEntry}// processResourceAttrAllowlist names the OTel Resource attributes we lift@@ -31,7 +31,7 @@ var processResourceAttrAllowlist = []string{func convertMetricPoints(projectId uuid.UUID, req *colmetricspb.ExportMetricsServiceRequest) convertedMetrics {var points []models.MetricPoint- seenEntries := make(map[string]repositories.MetricRegistrationEntry)+ seenEntries := make(map[string]transactional.MetricRegistrationEntry)for _, rm := range req.ResourceMetrics {resAttrs := rm.GetResource().GetAttributes()@@ -47,7 +47,7 @@ func convertMetricPoints(projectId uuid.UUID, req *colmetricspb.ExportMetricsSercase *metricspb.Metric_Gauge:points = appendNumberDataPoints(points, projectId, name, sn, resTags, data.Gauge.GetDataPoints())if _, ok := seenEntries[name]; !ok {- seenEntries[name] = repositories.MetricRegistrationEntry{+ seenEntries[name] = transactional.MetricRegistrationEntry{Name: name,Unit: unit,MetricType: "gauge",@@ -60,7 +60,7 @@ func convertMetricPoints(projectId uuid.UUID, req *colmetricspb.ExportMetricsSerif data.Sum.IsMonotonic {mt = "counter"}- seenEntries[name] = repositories.MetricRegistrationEntry{+ seenEntries[name] = transactional.MetricRegistrationEntry{Name: name,Unit: unit,MetricType: mt,@@ -90,14 +90,14 @@ func convertMetricPoints(projectId uuid.UUID, req *colmetricspb.ExportMetricsSeravgName := name + ".avg"countName := name + ".count"if _, ok := seenEntries[avgName]; !ok {- seenEntries[avgName] = repositories.MetricRegistrationEntry{+ seenEntries[avgName] = transactional.MetricRegistrationEntry{Name: avgName,Unit: unit,MetricType: "gauge",}}if _, ok := seenEntries[countName]; !ok {- seenEntries[countName] = repositories.MetricRegistrationEntry{+ seenEntries[countName] = transactional.MetricRegistrationEntry{Name: countName,Unit: "count",MetricType: "counter",@@ -108,7 +108,7 @@ func convertMetricPoints(projectId uuid.UUID, req *colmetricspb.ExportMetricsSer}}- entries := make([]repositories.MetricRegistrationEntry, 0, len(seenEntries))+ entries := make([]transactional.MetricRegistrationEntry, 0, len(seenEntries))for _, e := range seenEntries {entries = append(entries, e)}diff --git a/backend/app/controllers/otelcontrollers/otel.controller.go b/backend/app/controllers/otelcontrollers/otel.controller.goindex 5c279e6e..7d2b098c 100644--- a/backend/app/controllers/otelcontrollers/otel.controller.go+++ b/backend/app/controllers/otelcontrollers/otel.controller.go@@ -13,7 +13,7 @@ import ("github.com/tracewayapp/traceway/backend/app/models""github.com/tracewayapp/traceway/backend/app/monitoring""github.com/tracewayapp/traceway/backend/app/profiling"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry""github.com/tracewayapp/traceway/backend/app/services""github.com/tracewayapp/traceway/backend/app/storage""github.com/tracewayapp/traceway/backend/app/symbolicator/sourcemap/jsstack"@@ -111,31 +111,31 @@ func (o otelController) ExportTraces(c *gin.Context) {insertStart := time.Now()if len(endpoints) > 0 {- if err := repositories.EndpointRepository.InsertAsync(c, endpoints); err != nil {+ if err := telemetry.EndpointRepository.InsertAsync(c, endpoints); err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error inserting OTEL endpoints: %w", err))return}}if len(tasks) > 0 {- if err := repositories.TaskRepository.InsertAsync(c, tasks); err != nil {+ if err := telemetry.TaskRepository.InsertAsync(c, tasks); err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error inserting OTEL tasks: %w", err))return}}- if err := repositories.ExceptionStackTraceRepository.InsertAsync(c, exceptions); err != nil {+ if err := telemetry.ExceptionStackTraceRepository.InsertAsync(c, exceptions); err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error inserting OTEL exceptions: %w", err))return}- if err := repositories.SpanRepository.InsertAsync(c, spans); err != nil {+ if err := telemetry.SpanRepository.InsertAsync(c, spans); err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error inserting OTEL spans: %w", err))return}if len(aiTraces) > 0 {- if err := repositories.AiTraceRepository.InsertAsync(c, aiTraces); err != nil {+ if err := telemetry.AiTraceRepository.InsertAsync(c, aiTraces); err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error inserting OTEL ai traces: %w", err))return}@@ -236,7 +236,7 @@ func (o otelController) ExportMetrics(c *gin.Context) {insertMs := 0.0if len(result.Points) > 0 {insertStart := time.Now()- if err := repositories.MetricPointRepository.InsertAsync(c, result.Points); err != nil {+ if err := telemetry.MetricPointRepository.InsertAsync(c, result.Points); err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error inserting OTEL metric points: %w", err))return}@@ -307,7 +307,7 @@ func (o otelController) ExportLogs(c *gin.Context) {insertMs := 0.0if len(records) > 0 {insertStart := time.Now()- if err := repositories.LogRecordRepository.InsertAsync(c, records); err != nil {+ if err := telemetry.LogRecordRepository.InsertAsync(c, records); err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error inserting OTEL log records: %w", err))return}@@ -374,15 +374,15 @@ func (o otelController) ExportProfiles(c *gin.Context) {convertMs := msSince(convertStart)insertStart := time.Now()- if err := repositories.ProfileRepository.InsertStacksAsync(c, stacks); err != nil {+ if err := telemetry.ProfileRepository.InsertStacksAsync(c, stacks); err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error inserting OTEL profiling stacks: %w", err))return}- if err := repositories.ProfileRepository.InsertSamplesAsync(c, samples); err != nil {+ if err := telemetry.ProfileRepository.InsertSamplesAsync(c, samples); err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error inserting OTEL profiling samples: %w", err))return}- if err := repositories.ProfileRepository.InsertProfilesAsync(c, profiles); err != nil {+ if err := telemetry.ProfileRepository.InsertProfilesAsync(c, profiles); err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error inserting OTEL profiles: %w", err))return}diff --git a/backend/app/controllers/password_reset.controller.go b/backend/app/controllers/password_reset.controller.goindex 7d753595..5a3ae990 100644--- a/backend/app/controllers/password_reset.controller.go+++ b/backend/app/controllers/password_reset.controller.go@@ -1,12 +1,12 @@package controllersimport (+ "database/sql"+ "fmt""github.com/tracewayapp/traceway/backend/app/db""github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional""github.com/tracewayapp/traceway/backend/app/services"- "database/sql"- "fmt""net/http""time"@@ -29,7 +29,7 @@ func (c *passwordResetController) ForgotPassword(ctx *gin.Context) {return}- user, err := repositories.UserRepository.FindByEmail(tx, request.Email)+ user, err := transactional.UserRepository.FindByEmail(tx, request.Email)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to find user: %w", err))return@@ -48,7 +48,7 @@ func (c *passwordResetController) ForgotPassword(ctx *gin.Context) {token := uuid.New().String()expiresAt := time.Now().Add(resetTokenExpiry)- err = repositories.UserRepository.SetPasswordResetToken(tx, user.Id, token, expiresAt)+ err = transactional.UserRepository.SetPasswordResetToken(tx, user.Id, token, expiresAt)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to set reset token: %w", err))return@@ -67,7 +67,7 @@ func (c *passwordResetController) ValidateToken(ctx *gin.Context) {token := ctx.Param("token")user, err := db.ExecuteTransaction(func(tx *sql.Tx) (*models.User, error) {- return repositories.UserRepository.FindByPasswordResetToken(tx, token)+ return transactional.UserRepository.FindByPasswordResetToken(tx, token)})if err != nil {@@ -101,7 +101,7 @@ func (c *passwordResetController) ResetPassword(ctx *gin.Context) {return}- user, err := repositories.UserRepository.FindByPasswordResetToken(tx, token)+ user, err := transactional.UserRepository.FindByPasswordResetToken(tx, token)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to find user: %w", err))return@@ -123,13 +123,13 @@ func (c *passwordResetController) ResetPassword(ctx *gin.Context) {return}- err = repositories.UserRepository.UpdatePassword(tx, user.Id, hashedPassword)+ err = transactional.UserRepository.UpdatePassword(tx, user.Id, hashedPassword)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to update password: %w", err))return}- err = repositories.UserRepository.ClearPasswordResetToken(tx, user.Id)+ err = transactional.UserRepository.ClearPasswordResetToken(tx, user.Id)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("Failed to clear reset token: %w", err))returndiff --git a/backend/app/controllers/pat.controller.go b/backend/app/controllers/pat.controller.goindex b2b74161..ebb200ba 100644--- a/backend/app/controllers/pat.controller.go+++ b/backend/app/controllers/pat.controller.go@@ -13,7 +13,7 @@ import ("github.com/tracewayapp/traceway/backend/app/db""github.com/tracewayapp/traceway/backend/app/middleware""github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional""github.com/tracewayapp/traceway/backend/app/services/authserver")@@ -48,7 +48,7 @@ func (c *patController) Create(ctx *gin.Context) {expiresAt = &t}- if err := repositories.PersonalAccessTokenRepository.Create(tx, id, token, prefix, userId, name, expiresAt); err != nil {+ if err := transactional.PersonalAccessTokenRepository.Create(tx, id, token, prefix, userId, name, expiresAt); err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("create pat: %w", err))return}@@ -66,7 +66,7 @@ func (c *patController) Create(ctx *gin.Context) {func (c *patController) List(ctx *gin.Context) {userId := middleware.GetUserId(ctx)- tokens, err := repositories.PersonalAccessTokenRepository.ListByUser(db.DB, userId)+ tokens, err := transactional.PersonalAccessTokenRepository.ListByUser(db.DB, userId)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("list pats: %w", err))return@@ -79,7 +79,7 @@ func (c *patController) Revoke(ctx *gin.Context) {userId := middleware.GetUserId(ctx)id := ctx.Param("id")- rows, err := repositories.PersonalAccessTokenRepository.Revoke(tx, id, userId)+ rows, err := transactional.PersonalAccessTokenRepository.Revoke(tx, id, userId)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("revoke pat: %w", err))returndiff --git a/backend/app/controllers/profile.controller.go b/backend/app/controllers/profile.controller.goindex 234dddc1..159deb19 100644--- a/backend/app/controllers/profile.controller.go+++ b/backend/app/controllers/profile.controller.go@@ -13,7 +13,7 @@ import ("github.com/tracewayapp/traceway/backend/app/middleware""github.com/tracewayapp/traceway/backend/app/models""github.com/tracewayapp/traceway/backend/app/profiling"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry""github.com/tracewayapp/traceway/backend/app/services"traceway "go.tracewayapp.com")@@ -129,7 +129,7 @@ func (p profileController) FindGroupedByService(c *gin.Context) {search = ""}- groups, total, err := repositories.ProfileRepository.FindGroupedByService(c, projectId, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy, request.SortDirection, search)+ groups, total, err := telemetry.ProfileRepository.FindGroupedByService(c, projectId, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy, request.SortDirection, search)if err != nil {c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("error loading grouped profiles: %w", err))return@@ -169,7 +169,7 @@ func (p profileController) GetSeries(c *gin.Context) {return}- points, err := repositories.ProfileRepository.GetSeries(c, projectId, request.ServiceName, request.Type, request.FromDate, request.ToDate, request.IntervalMinutes, request.IsGauge, request.Labels, request.AppVersion, request.ServerName, request.Normalize)+ points, err := telemetry.ProfileRepository.GetSeries(c, projectId, request.ServiceName, request.Type, request.FromDate, request.ToDate, request.IntervalMinutes, request.IsGauge, request.Labels, request.AppVersion, request.ServerName, request.Normalize)if err != nil {c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("error loading profile series: %w", err))return@@ -207,7 +207,7 @@ func (p profileController) DiscoverTypes(c *gin.Context) {}}- types, err := repositories.ProfileRepository.DiscoverTypes(c, projectId, request.ServiceName, typesFrom, request.ToDate)+ types, err := telemetry.ProfileRepository.DiscoverTypes(c, projectId, request.ServiceName, typesFrom, request.ToDate)if err != nil {c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("error discovering profile types: %w", err))return@@ -242,7 +242,7 @@ func (p profileController) GetFlameGraph(c *gin.Context) {return}- rows, err := repositories.ProfileRepository.GetFlameGraph(c, projectId, request.ServiceName, request.Type, request.FromDate, request.ToDate, request.Labels, request.IsGauge, request.AppVersion, request.ServerName)+ rows, err := telemetry.ProfileRepository.GetFlameGraph(c, projectId, request.ServiceName, request.Type, request.FromDate, request.ToDate, request.Labels, request.IsGauge, request.AppVersion, request.ServerName)if err != nil {c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("error loading flame graph: %w", err))return@@ -282,7 +282,7 @@ func (p profileController) GetTopFunctions(c *gin.Context) {limit = 200}- rows, err := repositories.ProfileRepository.GetFlameGraph(c, projectId, request.ServiceName, request.Type, request.FromDate, request.ToDate, request.Labels, request.IsGauge, request.AppVersion, request.ServerName)+ rows, err := telemetry.ProfileRepository.GetFlameGraph(c, projectId, request.ServiceName, request.Type, request.FromDate, request.ToDate, request.Labels, request.IsGauge, request.AppVersion, request.ServerName)if err != nil {c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("error loading top functions: %w", err))return@@ -314,7 +314,7 @@ func (p profileController) DownloadPprof(c *gin.Context) {return}- rows, err := repositories.ProfileRepository.GetFlameGraph(c, projectId, request.ServiceName, request.Type, request.FromDate, request.ToDate, request.Labels, request.IsGauge, request.AppVersion, request.ServerName)+ rows, err := telemetry.ProfileRepository.GetFlameGraph(c, projectId, request.ServiceName, request.Type, request.FromDate, request.ToDate, request.Labels, request.IsGauge, request.AppVersion, request.ServerName)if err != nil {c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("error loading profile for export: %w", err))return@@ -399,7 +399,7 @@ func (p profileController) GetSeriesBreakdown(c *gin.Context) {return}- groups, err := repositories.ProfileRepository.GetSeriesBreakdown(c, projectId, request.ServiceName, request.Type, request.FromDate, request.ToDate, request.IntervalMinutes, request.IsGauge, request.Labels, request.AppVersion, request.ServerName, request.Normalize, request.Dimension, request.Limit)+ groups, err := telemetry.ProfileRepository.GetSeriesBreakdown(c, projectId, request.ServiceName, request.Type, request.FromDate, request.ToDate, request.IntervalMinutes, request.IsGauge, request.Labels, request.AppVersion, request.ServerName, request.Normalize, request.Dimension, request.Limit)if err != nil {c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("error loading profile series breakdown: %w", err))return@@ -433,7 +433,7 @@ func (p profileController) DiscoverDimensions(c *gin.Context) {return}- appVersions, serverNames, err := repositories.ProfileRepository.DiscoverDimensions(c, projectId, request.ServiceName, request.Type, request.FromDate, request.ToDate)+ appVersions, serverNames, err := telemetry.ProfileRepository.DiscoverDimensions(c, projectId, request.ServiceName, request.Type, request.FromDate, request.ToDate)if err != nil {c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("error discovering profile dimensions: %w", err))return@@ -469,7 +469,7 @@ func (p profileController) DiscoverLabels(c *gin.Context) {additional = proj.ProfileLabelAllowlist}- labels, err := repositories.ProfileRepository.DiscoverLabels(c, projectId, request.ServiceName, request.Type, request.FromDate, request.ToDate, profiling.LabelAllowKeys(additional))+ labels, err := telemetry.ProfileRepository.DiscoverLabels(c, projectId, request.ServiceName, request.Type, request.FromDate, request.ToDate, profiling.LabelAllowKeys(additional))if err != nil {c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("error discovering profile labels: %w", err))returndiff --git a/backend/app/controllers/project.controller.go b/backend/app/controllers/project.controller.goindex e7f15407..39e0b20f 100644--- a/backend/app/controllers/project.controller.go+++ b/backend/app/controllers/project.controller.go@@ -1,15 +1,15 @@package controllersimport (+ "database/sql"+ "errors"+ "fmt""github.com/tracewayapp/traceway/backend/app/cache"+ "github.com/tracewayapp/traceway/backend/app/db""github.com/tracewayapp/traceway/backend/app/middleware""github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/db""github.com/tracewayapp/traceway/backend/app/profiling"- "github.com/tracewayapp/traceway/backend/app/repositories"- "database/sql"- "errors"- "fmt"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional""net/http""regexp""strings"@@ -29,27 +29,27 @@ var validFrameworks = map[string]bool{"stdlib": true,"custom": true,// JavaScript frameworks- "react": true,- "svelte": true,- "vuejs": true,- "nextjs": true,- "nestjs": true,- "express": true,- "remix": true,- "jquery": true,- "react-native": true,- "hono": true,- "cloudflare": true,- "opentelemetry": true,+ "react": true,+ "svelte": true,+ "vuejs": true,+ "nextjs": true,+ "nestjs": true,+ "express": true,+ "remix": true,+ "jquery": true,+ "react-native": true,+ "hono": true,+ "cloudflare": true,+ "opentelemetry": true,// PHP frameworks- "symfony": true,- "laravel": true,+ "symfony": true,+ "laravel": true,// Python frameworks- "django": true,+ "django": true,// Mobile frameworks- "flutter": true,- "android": true,- "ios": true,+ "flutter": true,+ "android": true,+ "ios": true,}// Project name validation regex: allows alphanumeric, spaces, hyphens, and underscores@@ -107,7 +107,7 @@ func (p projectController) ListProjects(c *gin.Context) {userId := middleware.GetUserId(c)projectsWithBackendUrl, err := db.ExecuteTransaction(func(tx *sql.Tx) ([]*models.ProjectWithBackendUrl, error) {- return repositories.ProjectRepository.FindAllWithBackendUrlByUserId(tx, userId)+ return transactional.ProjectRepository.FindAllWithBackendUrlByUserId(tx, userId)})if err != nil {c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("error fetching projects: %w", err))@@ -149,7 +149,7 @@ func (p projectController) CreateProject(c *gin.Context) {}project, err := db.ExecuteTransaction(func(tx *sql.Tx) (*models.Project, error) {- currentProject, err := repositories.ProjectRepository.FindById(tx, projectId)+ currentProject, err := transactional.ProjectRepository.FindById(tx, projectId)if err != nil {return nil, err}@@ -161,7 +161,7 @@ func (p projectController) CreateProject(c *gin.Context) {return nil, err}}- return repositories.ProjectRepository.CreateWithOrganization(tx, request.Name, request.Framework, *currentProject.OrganizationId)+ return transactional.ProjectRepository.CreateWithOrganization(tx, request.Name, request.Framework, *currentProject.OrganizationId)})if err != nil {var limitErr *LimitExceededError@@ -250,7 +250,7 @@ func (p projectController) UpdateProject(c *gin.Context) {}project, err := db.ExecuteTransaction(func(tx *sql.Tx) (*models.Project, error) {- return repositories.ProjectRepository.Update(tx, projectId, request.Name, request.Framework, request.DropHealthyHealthchecks, healthcheckPaths, profileLabelAllowlist)+ return transactional.ProjectRepository.Update(tx, projectId, request.Name, request.Framework, request.DropHealthyHealthchecks, healthcheckPaths, profileLabelAllowlist)})if err != nil {c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("error updating project: %w", err))@@ -276,7 +276,7 @@ func (p projectController) DeleteProject(c *gin.Context) {}nameMatched, err := db.ExecuteTransaction(func(tx *sql.Tx) (bool, error) {- project, err := repositories.ProjectRepository.FindById(tx, projectId)+ project, err := transactional.ProjectRepository.FindById(tx, projectId)if err != nil {return false, err}@@ -286,7 +286,7 @@ func (p projectController) DeleteProject(c *gin.Context) {if project.Name != request.Name {return false, nil}- if err := repositories.ProjectRepository.Delete(tx, projectId); err != nil {+ if err := transactional.ProjectRepository.Delete(tx, projectId); err != nil {return false, err}return true, nil@@ -313,7 +313,7 @@ func (p projectController) GenerateSourceMapToken(c *gin.Context) {}token, err := db.ExecuteTransaction(func(tx *sql.Tx) (string, error) {- return repositories.ProjectRepository.GenerateSourceMapToken(tx, projectId)+ return transactional.ProjectRepository.GenerateSourceMapToken(tx, projectId)})if err != nil {c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to generate source map token: %w", err))diff --git a/backend/app/controllers/session.controller.go b/backend/app/controllers/session.controller.goindex ff38562f..69d2a7b0 100644--- a/backend/app/controllers/session.controller.go+++ b/backend/app/controllers/session.controller.go@@ -6,7 +6,7 @@ import ("github.com/tracewayapp/traceway/backend/app/middleware""github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry""github.com/gin-gonic/gin"traceway "go.tracewayapp.com"@@ -42,16 +42,16 @@ func (s sessionController) FindAllSessions(c *gin.Context) {return}- filters := make([]repositories.SessionAttributeFilter, 0, len(request.AttributeFilters))+ filters := make([]telemetry.SessionAttributeFilter, 0, len(request.AttributeFilters))for _, f := range request.AttributeFilters {if f.Key == "" {continue}- filters = append(filters, repositories.SessionAttributeFilter{Key: f.Key, Value: f.Value})+ filters = append(filters, telemetry.SessionAttributeFilter{Key: f.Key, Value: f.Value})}span := traceway.StartSpan(c, "loading sessions")- sessions, total, err := repositories.SessionRepository.FindAll(c, projectId, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy, request.SortDirection, request.Search, filters)+ sessions, total, err := telemetry.SessionRepository.FindAll(c, projectId, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy, request.SortDirection, request.Search, filters)span.End()if err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading sessions: %w", err))diff --git a/backend/app/controllers/session_detail.controller.go b/backend/app/controllers/session_detail.controller.goindex 255b6e90..155c0d55 100644--- a/backend/app/controllers/session_detail.controller.go+++ b/backend/app/controllers/session_detail.controller.go@@ -8,7 +8,7 @@ import ("github.com/tracewayapp/traceway/backend/app/middleware""github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry""github.com/tracewayapp/traceway/backend/app/storage""github.com/gin-gonic/gin"@@ -64,9 +64,9 @@ func (s sessionDetailController) GetSessionDetail(c *gin.Context) {_ = c.ShouldBindJSON(&request)span := traceway.StartSpan(c, "loading session")- session, err := repositories.SessionRepository.FindById(c, projectId, sessionId, request.StartedAt)+ session, err := telemetry.SessionRepository.FindById(c, projectId, sessionId, request.StartedAt)if session == nil && err == nil && request.StartedAt != nil {- session, err = repositories.SessionRepository.FindById(c, projectId, sessionId, nil)+ session, err = telemetry.SessionRepository.FindById(c, projectId, sessionId, nil)}span.End()if err != nil {@@ -79,7 +79,7 @@ func (s sessionDetailController) GetSessionDetail(c *gin.Context) {}span = traceway.StartSpan(c, "loading session exceptions")- exceptions, err := repositories.ExceptionStackTraceRepository.FindAllBySessionId(c, projectId, sessionId)+ exceptions, err := telemetry.ExceptionStackTraceRepository.FindAllBySessionId(c, projectId, sessionId)span.End()if err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading session exceptions: %w", err))@@ -117,7 +117,7 @@ func (s sessionDetailController) GetSessionRecording(c *gin.Context) {}span := traceway.StartSpan(c, "loading session segments")- segments, err := repositories.SessionRecordingRepository.FindBySessionId(c, projectId, sessionId)+ segments, err := telemetry.SessionRecordingRepository.FindBySessionId(c, projectId, sessionId)span.End()if err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading session segments: %w", err))diff --git a/backend/app/controllers/task.controller.go b/backend/app/controllers/task.controller.goindex 27f12e0d..d28c5c79 100644--- a/backend/app/controllers/task.controller.go+++ b/backend/app/controllers/task.controller.go@@ -3,7 +3,7 @@ package controllersimport ("github.com/tracewayapp/traceway/backend/app/middleware""github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry""net/http""net/url""time"@@ -52,7 +52,7 @@ func (e taskController) FindAllTasks(c *gin.Context) {}span := traceway.StartSpan(c, "loading tasks")- tasks, total, err := repositories.TaskRepository.FindAll(c, projectId, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy)+ tasks, total, err := telemetry.TaskRepository.FindAll(c, projectId, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy)span.End()if err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading tasks: %w", err))@@ -84,7 +84,7 @@ func (e taskController) FindGroupedByTaskName(c *gin.Context) {}span := traceway.StartSpan(c, "loading grouped tasks")- stats, total, err := repositories.TaskRepository.FindGroupedByTaskName(c, projectId, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy, request.SortDirection, request.Search, request.RootFilter)+ stats, total, err := telemetry.TaskRepository.FindGroupedByTaskName(c, projectId, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy, request.SortDirection, request.Search, request.RootFilter)span.End()if err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading stats by name: %w", err))@@ -128,7 +128,7 @@ func (e taskController) FindByTaskName(c *gin.Context) {}span := traceway.StartSpan(c, "loading task instances")- tasks, total, err := repositories.TaskRepository.FindByTaskName(c, projectId, taskName, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy, request.SortDirection)+ tasks, total, err := telemetry.TaskRepository.FindByTaskName(c, projectId, taskName, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy, request.SortDirection)span.End()if err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading tasks by name: %w", err))@@ -137,7 +137,7 @@ func (e taskController) FindByTaskName(c *gin.Context) {// Get aggregate stats for this taskspan = traceway.StartSpan(c, "loading task stats")- stats, err := repositories.TaskRepository.GetTaskStats(c, projectId, taskName, request.FromDate, request.ToDate)+ stats, err := telemetry.TaskRepository.GetTaskStats(c, projectId, taskName, request.FromDate, request.ToDate)span.End()if err != nil {// Don't fail the request if stats fail, just return nil statsdiff --git a/backend/app/controllers/task_detail.controller.go b/backend/app/controllers/task_detail.controller.goindex 545265ef..9b4fface 100644--- a/backend/app/controllers/task_detail.controller.go+++ b/backend/app/controllers/task_detail.controller.go@@ -6,7 +6,7 @@ import ("github.com/tracewayapp/traceway/backend/app/middleware""github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry""github.com/gin-gonic/gin""github.com/google/uuid"@@ -59,9 +59,9 @@ func (t taskDetailController) GetTaskDetail(c *gin.Context) {// Get taskspan := traceway.StartSpan(c, "loading task")- task, err := repositories.TaskRepository.FindById(c, projectId, taskId, request.RecordedAt)+ task, err := telemetry.TaskRepository.FindById(c, projectId, taskId, request.RecordedAt)if task == nil && err == nil && request.RecordedAt != nil {- task, err = repositories.TaskRepository.FindById(c, projectId, taskId, nil)+ task, err = telemetry.TaskRepository.FindById(c, projectId, taskId, nil)}span.End()if err != nil {@@ -77,7 +77,7 @@ func (t taskDetailController) GetTaskDetail(c *gin.Context) {// Get spans (flat list ordered by start_time)span = traceway.StartSpan(c, "loading spans")- spans, err := repositories.SpanRepository.FindByTraceId(c, projectId, taskId, &recordedAt)+ spans, err := telemetry.SpanRepository.FindByTraceId(c, projectId, taskId, &recordedAt)span.End()if err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading spans: %w", err))@@ -89,7 +89,7 @@ func (t taskDetailController) GetTaskDetail(c *gin.Context) {var messages []TaskMessageInfospan = traceway.StartSpan(c, "loading exceptions")- allExceptions, err := repositories.ExceptionStackTraceRepository.FindAllByTraceId(c, projectId, taskId, &recordedAt)+ allExceptions, err := telemetry.ExceptionStackTraceRepository.FindAllByTraceId(c, projectId, taskId, &recordedAt)span.End()if err != nil {c.AbortWithError(500, traceway.NewStackTraceErrorf("error loading allExceptions: %w", err))diff --git a/backend/app/controllers/widget.controller.go b/backend/app/controllers/widget.controller.goindex 606a7c83..1a27b062 100644--- a/backend/app/controllers/widget.controller.go+++ b/backend/app/controllers/widget.controller.go@@ -10,7 +10,7 @@ import ("github.com/tracewayapp/traceway/backend/app/db""github.com/tracewayapp/traceway/backend/app/middleware""github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional""github.com/gin-gonic/gin"traceway "go.tracewayapp.com"@@ -60,7 +60,7 @@ func (c *widgetController) Add(ctx *gin.Context) {tx := db.GetTx(ctx)- group, err := repositories.WidgetGroupRepository.FindById(tx, groupId)+ group, err := transactional.WidgetGroupRepository.FindById(tx, groupId)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to add widget: %w", err))return@@ -70,7 +70,7 @@ func (c *widgetController) Add(ctx *gin.Context) {return}- existing, err := repositories.WidgetGroupRepository.FindWidgetsByGroup(tx, groupId)+ existing, err := transactional.WidgetGroupRepository.FindWidgetsByGroup(tx, groupId)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to add widget: %w", err))return@@ -85,7 +85,7 @@ func (c *widgetController) Add(ctx *gin.Context) {CreatedAt: time.Now().UTC(),UpdatedAt: time.Now().UTC(),}- id, err := repositories.WidgetGroupRepository.CreateWidget(tx, w)+ id, err := transactional.WidgetGroupRepository.CreateWidget(tx, w)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to add widget: %w", err))return@@ -137,7 +137,7 @@ func (c *widgetController) Update(ctx *gin.Context) {tx := db.GetTx(ctx)- group, err := repositories.WidgetGroupRepository.FindById(tx, groupId)+ group, err := transactional.WidgetGroupRepository.FindById(tx, groupId)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to update widget: %w", err))return@@ -147,7 +147,7 @@ func (c *widgetController) Update(ctx *gin.Context) {return}- widget, err := repositories.WidgetGroupRepository.FindWidgetById(tx, widgetId)+ widget, err := transactional.WidgetGroupRepository.FindWidgetById(tx, widgetId)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to update widget: %w", err))return@@ -164,7 +164,7 @@ func (c *widgetController) Update(ctx *gin.Context) {}widget.UpdatedAt = time.Now().UTC()- if err := repositories.WidgetGroupRepository.UpdateWidget(tx, widget); err != nil {+ if err := transactional.WidgetGroupRepository.UpdateWidget(tx, widget); err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to update widget: %w", err))return}@@ -198,7 +198,7 @@ func (c *widgetController) Reorder(ctx *gin.Context) {tx := db.GetTx(ctx)- group, err := repositories.WidgetGroupRepository.FindById(tx, groupId)+ group, err := transactional.WidgetGroupRepository.FindById(tx, groupId)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to reorder widgets: %w", err))return@@ -208,7 +208,7 @@ func (c *widgetController) Reorder(ctx *gin.Context) {return}- allWidgets, err := repositories.WidgetGroupRepository.FindWidgetsByGroup(tx, groupId)+ allWidgets, err := transactional.WidgetGroupRepository.FindWidgetsByGroup(tx, groupId)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to reorder widgets: %w", err))return@@ -241,7 +241,7 @@ func (c *widgetController) Reorder(ctx *gin.Context) {}w.Position = positionw.UpdatedAt = now- if err := repositories.WidgetGroupRepository.UpdateWidget(tx, w); err != nil {+ if err := transactional.WidgetGroupRepository.UpdateWidget(tx, w); err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to reorder widgets: %w", err))return}@@ -273,7 +273,7 @@ func (c *widgetController) Delete(ctx *gin.Context) {tx := db.GetTx(ctx)- group, err := repositories.WidgetGroupRepository.FindById(tx, groupId)+ group, err := transactional.WidgetGroupRepository.FindById(tx, groupId)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to delete widget: %w", err))return@@ -283,7 +283,7 @@ func (c *widgetController) Delete(ctx *gin.Context) {return}- widget, err := repositories.WidgetGroupRepository.FindWidgetById(tx, widgetId)+ widget, err := transactional.WidgetGroupRepository.FindWidgetById(tx, widgetId)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to delete widget: %w", err))return@@ -293,12 +293,12 @@ func (c *widgetController) Delete(ctx *gin.Context) {return}- if err := repositories.WidgetGroupRepository.DeleteStarredByWidgetId(tx, widgetId); err != nil {+ if err := transactional.WidgetGroupRepository.DeleteStarredByWidgetId(tx, widgetId); err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to delete widget: %w", err))return}- if err := repositories.WidgetGroupRepository.DeleteWidget(tx, widgetId); err != nil {+ if err := transactional.WidgetGroupRepository.DeleteWidget(tx, widgetId); err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to delete widget: %w", err))return}@@ -329,7 +329,7 @@ func (c *widgetController) ToggleStar(ctx *gin.Context) {tx := db.GetTx(ctx)- group, err := repositories.WidgetGroupRepository.FindById(tx, groupId)+ group, err := transactional.WidgetGroupRepository.FindById(tx, groupId)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to toggle star: %w", err))return@@ -339,7 +339,7 @@ func (c *widgetController) ToggleStar(ctx *gin.Context) {return}- widget, err := repositories.WidgetGroupRepository.FindWidgetById(tx, widgetId)+ widget, err := transactional.WidgetGroupRepository.FindWidgetById(tx, widgetId)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to toggle star: %w", err))return@@ -349,14 +349,14 @@ func (c *widgetController) ToggleStar(ctx *gin.Context) {return}- starred, err := repositories.WidgetGroupRepository.FindStarredByWidgetId(tx, projectId, widgetId)+ starred, err := transactional.WidgetGroupRepository.FindStarredByWidgetId(tx, projectId, widgetId)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to toggle star: %w", err))return}if starred != nil {- if err := repositories.WidgetGroupRepository.DeleteStarredByWidgetId(tx, widgetId); err != nil {+ if err := transactional.WidgetGroupRepository.DeleteStarredByWidgetId(tx, widgetId); err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to toggle star: %w", err))return}@@ -364,7 +364,7 @@ func (c *widgetController) ToggleStar(ctx *gin.Context) {return}- allStarred, err := repositories.WidgetGroupRepository.FindStarredByProject(tx, projectId)+ allStarred, err := transactional.WidgetGroupRepository.FindStarredByProject(tx, projectId)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to toggle star: %w", err))return@@ -396,7 +396,7 @@ func (c *widgetController) ToggleStar(ctx *gin.Context) {Size: cfg.Size,CreatedAt: time.Now().UTC(),}- if err := repositories.WidgetGroupRepository.CreateStarred(tx, row); err != nil {+ if err := transactional.WidgetGroupRepository.CreateStarred(tx, row); err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to toggle star: %w", err))return}@@ -413,7 +413,7 @@ func (c *widgetController) ListStarred(ctx *gin.Context) {tx := db.GetTx(ctx)- widgets, err := repositories.WidgetGroupRepository.FindStarredWidgetsByProject(tx, projectId)+ widgets, err := transactional.WidgetGroupRepository.FindStarredWidgetsByProject(tx, projectId)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to list starred widgets: %w", err))return@@ -441,7 +441,7 @@ func (c *widgetController) ReorderStarred(ctx *gin.Context) {tx := db.GetTx(ctx)- starred, err := repositories.WidgetGroupRepository.FindStarredByProject(tx, projectId)+ starred, err := transactional.WidgetGroupRepository.FindStarredByProject(tx, projectId)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to reorder starred widgets: %w", err))return@@ -472,7 +472,7 @@ func (c *widgetController) ReorderStarred(ctx *gin.Context) {continue}s.Position = position- if err := repositories.WidgetGroupRepository.UpdateStarred(tx, s); err != nil {+ if err := transactional.WidgetGroupRepository.UpdateStarred(tx, s); err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to reorder starred widgets: %w", err))return}@@ -517,7 +517,7 @@ func (c *widgetController) UpdateStarredLayout(ctx *gin.Context) {tx := db.GetTx(ctx)- starred, err := repositories.WidgetGroupRepository.FindStarredByWidgetId(tx, projectId, widgetId)+ starred, err := transactional.WidgetGroupRepository.FindStarredByWidgetId(tx, projectId, widgetId)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to update starred widget layout: %w", err))return@@ -530,7 +530,7 @@ func (c *widgetController) UpdateStarredLayout(ctx *gin.Context) {starred.ColSpan = req.ColSpanstarred.Size = req.Size- if err := repositories.WidgetGroupRepository.UpdateStarred(tx, starred); err != nil {+ if err := transactional.WidgetGroupRepository.UpdateStarred(tx, starred); err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to update starred widget layout: %w", err))return}diff --git a/backend/app/controllers/widget_group.controller.go b/backend/app/controllers/widget_group.controller.goindex 0eff61be..feafec45 100644--- a/backend/app/controllers/widget_group.controller.go+++ b/backend/app/controllers/widget_group.controller.go@@ -11,7 +11,7 @@ import ("github.com/tracewayapp/traceway/backend/app/db""github.com/tracewayapp/traceway/backend/app/middleware""github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional""github.com/gin-gonic/gin""github.com/google/uuid"@@ -29,13 +29,13 @@ func (c *widgetGroupController) List(ctx *gin.Context) {tx := db.GetTx(ctx)- list, err := repositories.WidgetGroupRepository.FindByProject(tx, projectId)+ list, err := transactional.WidgetGroupRepository.FindByProject(tx, projectId)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to list widget groups: %w", err))return}- project, err := repositories.ProjectRepository.FindById(tx, projectId)+ project, err := transactional.ProjectRepository.FindById(tx, projectId)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to find project: %w", err))return@@ -62,7 +62,7 @@ func (c *widgetGroupController) PopulateDefaults(ctx *gin.Context) {tx := db.GetTx(ctx)- existing, err := repositories.WidgetGroupRepository.FindByProject(tx, projectId)+ existing, err := transactional.WidgetGroupRepository.FindByProject(tx, projectId)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to list widget groups: %w", err))return@@ -77,7 +77,7 @@ func (c *widgetGroupController) PopulateDefaults(ctx *gin.Context) {return}- list, err := repositories.WidgetGroupRepository.FindByProject(tx, projectId)+ list, err := transactional.WidgetGroupRepository.FindByProject(tx, projectId)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to list widget groups: %w", err))return@@ -116,7 +116,7 @@ func (c *widgetGroupController) Create(ctx *gin.Context) {tx := db.GetTx(ctx)- existing, err := repositories.WidgetGroupRepository.FindByProject(tx, projectId)+ existing, err := transactional.WidgetGroupRepository.FindByProject(tx, projectId)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to check duplicate widget group name: %w", err))return@@ -143,7 +143,7 @@ func (c *widgetGroupController) Create(ctx *gin.Context) {CreatedAt: time.Now().UTC(),UpdatedAt: time.Now().UTC(),}- id, err := repositories.WidgetGroupRepository.Create(tx, g)+ id, err := transactional.WidgetGroupRepository.Create(tx, g)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to create widget group: %w", err))return@@ -169,7 +169,7 @@ func (c *widgetGroupController) GetWithWidgets(ctx *gin.Context) {tx := db.GetTx(ctx)- group, err := repositories.WidgetGroupRepository.FindById(tx, id)+ group, err := transactional.WidgetGroupRepository.FindById(tx, id)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to get widget group: %w", err))return@@ -179,7 +179,7 @@ func (c *widgetGroupController) GetWithWidgets(ctx *gin.Context) {return}- widgets, err := repositories.WidgetGroupRepository.FindWidgetsByGroupWithStar(tx, id)+ widgets, err := transactional.WidgetGroupRepository.FindWidgetsByGroupWithStar(tx, id)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to get widget group widgets: %w", err))return@@ -228,7 +228,7 @@ func (c *widgetGroupController) Update(ctx *gin.Context) {tx := db.GetTx(ctx)- existing, err := repositories.WidgetGroupRepository.FindById(tx, id)+ existing, err := transactional.WidgetGroupRepository.FindById(tx, id)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to update widget group: %w", err))return@@ -238,7 +238,7 @@ func (c *widgetGroupController) Update(ctx *gin.Context) {return}- allGroups, err := repositories.WidgetGroupRepository.FindByProject(tx, projectId)+ allGroups, err := transactional.WidgetGroupRepository.FindByProject(tx, projectId)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to check duplicate widget group name: %w", err))return@@ -254,7 +254,7 @@ func (c *widgetGroupController) Update(ctx *gin.Context) {existing.Description = req.Descriptionexisting.UpdatedAt = time.Now().UTC()- if err := repositories.WidgetGroupRepository.Update(tx, existing); err != nil {+ if err := transactional.WidgetGroupRepository.Update(tx, existing); err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to update widget group: %w", err))return}@@ -278,7 +278,7 @@ func (c *widgetGroupController) Delete(ctx *gin.Context) {tx := db.GetTx(ctx)- existing, err := repositories.WidgetGroupRepository.FindById(tx, id)+ existing, err := transactional.WidgetGroupRepository.FindById(tx, id)if err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to delete widget group: %w", err))return@@ -292,17 +292,17 @@ func (c *widgetGroupController) Delete(ctx *gin.Context) {// then the group itself. Don't lean on the FK cascade — explicit deletes// are easier to audit and survive future schema migrations that might// drop or alter the cascade rule.- if err := repositories.WidgetGroupRepository.DeleteStarredByGroup(tx, id); err != nil {+ if err := transactional.WidgetGroupRepository.DeleteStarredByGroup(tx, id); err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to delete widget group starred widgets: %w", err))return}- if err := repositories.WidgetGroupRepository.DeleteWidgetsByGroup(tx, id); err != nil {+ if err := transactional.WidgetGroupRepository.DeleteWidgetsByGroup(tx, id); err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to delete widget group widgets: %w", err))return}- if err := repositories.WidgetGroupRepository.Delete(tx, id); err != nil {+ if err := transactional.WidgetGroupRepository.Delete(tx, id); err != nil {ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to delete widget group: %w", err))return}@@ -311,7 +311,7 @@ func (c *widgetGroupController) Delete(ctx *gin.Context) {}func ensureDefaultWidgetGroups(tx *sql.Tx, projectId uuid.UUID) error {- project, err := repositories.ProjectRepository.FindById(tx, projectId)+ project, err := transactional.ProjectRepository.FindById(tx, projectId)if err != nil {return err}@@ -416,7 +416,7 @@ func ensureDefaultWidgetGroups(tx *sql.Tx, projectId uuid.UUID) error {CreatedAt: now,UpdatedAt: now,}- groupId, err := repositories.WidgetGroupRepository.Create(tx, g)+ groupId, err := transactional.WidgetGroupRepository.Create(tx, g)if err != nil {return err}@@ -436,7 +436,7 @@ func ensureDefaultWidgetGroups(tx *sql.Tx, projectId uuid.UUID) error {CreatedAt: now,UpdatedAt: now,}- if _, err := repositories.WidgetGroupRepository.CreateWidget(tx, widget); err != nil {+ if _, err := transactional.WidgetGroupRepository.CreateWidget(tx, widget); err != nil {return err}}diff --git a/backend/app/db/db.go b/backend/app/db/db.goindex 71e3a249..cb1bb409 100644--- a/backend/app/db/db.go+++ b/backend/app/db/db.go@@ -15,10 +15,25 @@ var DB *sql.DB // PostgreSQL-replacement: relational/config data (transvar TelemetryDB *sql.DB // ClickHouse-replacement: append-only telemetry data (non-transactional)var Driver lit.Driver = lit.PostgreSQL+var telemetryIsDuckDB bool+func IsSQLite() bool {return Driver == lit.SQLite}+// Init opens the main (transactional) database selected by the transactional_* build axis, then+// the telemetry database selected by the telemetry_* build axis.+func Init() error {+ if err := initMainDB(); err != nil {+ return err+ }+ return initTelemetryDB()+}++func IsDuckDBTelemetry() bool {+ return telemetryIsDuckDB+}+func initPostgres() error {cfg := config.Config@@ -64,6 +79,7 @@ func GetDB() *sql.DB {}const TransactionContextKey = "dbTx"+func GetTx(ctx context.Context) *sql.Tx {if tx, ok := ctx.Value(TransactionContextKey).(*sql.Tx); ok {return txdiff --git a/backend/app/db/db_pgch.go b/backend/app/db/db_pgch.godeleted file mode 100644index 25938f14..00000000--- a/backend/app/db/db_pgch.go+++ /dev/null@@ -1,7 +0,0 @@-//go:build pgch--package db--func Init() error {- return initPostgres()-}diff --git a/backend/app/db/db_sqlite.go b/backend/app/db/db_sqlite_open.gosimilarity index 62%rename from backend/app/db/db_sqlite.gorename to backend/app/db/db_sqlite_open.goindex 4d83d1f3..4051a5ee 100644--- a/backend/app/db/db_sqlite.go+++ b/backend/app/db/db_sqlite_open.go@@ -1,4 +1,4 @@-//go:build !pgch+//go:build !transactional_pg || (!telemetry_ch && !telemetry_duckdb)package db@@ -7,52 +7,9 @@ import ("fmt""strings"- "github.com/tracewayapp/traceway/backend/app/config"- "github.com/tracewayapp/lit/v2"_ "modernc.org/sqlite")-func Init() error {- cfg := config.Config- if cfg.DBType == "sqlite" {- return initSQLite()- }- return initPostgres()-}--func initSQLite() error {- path := config.Config.SQLitePath- if path == "" {- path = "./traceway.db"- }-- mainDB, err := openSQLite(path, false)- if err != nil {- return err- }- DB = mainDB- Driver = lit.SQLite- config.Logf("SQLite database opened at %s", path)-- telemetryPath := strings.TrimSuffix(path, ".db") + "_telemetry.db"- if path == ":memory:" {- telemetryPath = ":memory:"- }- telDB, err := openSQLite(telemetryPath, true)- if err != nil {- return err- }- TelemetryDB = telDB- config.Logf("SQLite telemetry database opened at %s", telemetryPath)-- return nil-}--// openSQLite opens a SQLite database with pragmas tuned for its role.-// The main DB gets foreign-key enforcement and the safest fsync mode; the-// telemetry DB relaxes synchronous to NORMAL and grows the page cache because-// it is append-only and cheaply re-derivable from clients on a hard crash.-//// Pragmas go on the DSN (modernc.org/sqlite supports `_pragma=name(value)`)// rather than via db.Exec because Exec only configures the first pooled// connection — once SetMaxOpenConns goes above 1 new connections woulddiff --git a/backend/app/db/db_sqlite_pool_test.go b/backend/app/db/db_sqlite_pool_test.goindex 8afde0b9..dd96f67b 100644--- a/backend/app/db/db_sqlite_pool_test.go+++ b/backend/app/db/db_sqlite_pool_test.go@@ -1,4 +1,4 @@-//go:build !pgch+//go:build !transactional_pg || (!telemetry_ch && !telemetry_duckdb)package dbdiff --git a/backend/app/db/db_telemetry_ch.go b/backend/app/db/db_telemetry_ch.gonew file mode 100644index 00000000..5b4d5fd6--- /dev/null+++ b/backend/app/db/db_telemetry_ch.go@@ -0,0 +1,9 @@+//go:build telemetry_ch++package db++// ClickHouse connects through chdb.Init from cmd/run.go; there is no+// TelemetryDB handle in this build.+func initTelemetryDB() error {+ return nil+}diff --git a/backend/app/db/db_telemetry_duckdb.go b/backend/app/db/db_telemetry_duckdb.gonew file mode 100644index 00000000..5205ab63--- /dev/null+++ b/backend/app/db/db_telemetry_duckdb.go@@ -0,0 +1,99 @@+//go:build telemetry_duckdb++package db++import (+ "context"+ "database/sql"+ "fmt"+ "net/url"+ "os"+ "strings"++ "github.com/duckdb/duckdb-go/v2"+ "github.com/tracewayapp/traceway/backend/app/config"+)++// DuckDBConnector is retained so repositories can open a dedicated driver.Conn+// for the Appender bulk-insert API, which is not reachable through database/sql.+var DuckDBConnector *duckdb.Connector++var duckDBPath string++const duckDBMaxReadConns = 4++func initTelemetryDB() error {+ if config.Config.DBType != "sqlite" {+ return nil+ }++ path := config.Config.SQLitePath+ if path == "" {+ path = "./traceway.db"+ }++ telemetryPath := strings.TrimSuffix(path, ".db") + "_telemetry.duckdb"+ if path == ":memory:" {+ telemetryPath = ""+ }+ if err := openDuckDB(telemetryPath); err != nil {+ return err+ }+ config.Logf("DuckDB telemetry database opened at %s", telemetryPath)++ return nil+}++func openDuckDB(path string) error {+ q := url.Values{}+ // Safe to drop: every telemetry read query has an explicit ORDER BY.+ q.Set("preserve_insertion_order", "false")+ if v := strings.TrimSpace(config.Config.DuckDBMemoryLimit); v != "" {+ q.Set("memory_limit", v)+ }+ if v := strings.TrimSpace(config.Config.DuckDBThreads); v != "" {+ q.Set("threads", v)+ }+ if v := strings.TrimSpace(config.Config.DuckDBCheckpointThreshold); v != "" {+ q.Set("checkpoint_threshold", v)+ }+ dsn := path + "?" + q.Encode()++ connector, err := duckdb.NewConnector(dsn, nil)+ if err != nil {+ return fmt.Errorf("failed to open duckdb at %s: %w", path, err)+ }++ d := sql.OpenDB(connector)+ d.SetMaxOpenConns(duckDBMaxReadConns)+ d.SetMaxIdleConns(duckDBMaxReadConns)+ if err := d.Ping(); err != nil {+ return fmt.Errorf("failed to ping duckdb at %s: %w", path, err)+ }++ DuckDBConnector = connector+ TelemetryDB = d+ telemetryIsDuckDB = true+ duckDBPath = path+ telemetryEngineStatsFn = duckDBEngineStats+ return nil+}++func duckDBEngineStats(ctx context.Context) TelemetryEngineStats {+ var s TelemetryEngineStats+ if fi, err := os.Stat(duckDBPath); err == nil {+ s.DBSizeBytes = fi.Size()+ }+ if fi, err := os.Stat(duckDBPath + ".wal"); err == nil {+ s.WALSizeBytes = fi.Size()+ }+ var mem int64+ if err := TelemetryDB.QueryRowContext(ctx, "SELECT COALESCE(CAST(SUM(memory_usage_bytes) AS BIGINT), 0) FROM duckdb_memory()").Scan(&mem); err == nil {+ s.MemoryUsedBytes = mem+ }+ st := TelemetryDB.Stats()+ s.ReadPoolInUse = st.InUse+ s.ReadPoolWaitCount = st.WaitCount+ s.ReadPoolWaitMs = st.WaitDuration.Milliseconds()+ return s+}diff --git a/backend/app/db/db_telemetry_sqlite.go b/backend/app/db/db_telemetry_sqlite.gonew file mode 100644index 00000000..f7ae7f85--- /dev/null+++ b/backend/app/db/db_telemetry_sqlite.go@@ -0,0 +1,33 @@+//go:build !telemetry_ch && !telemetry_duckdb++package db++import (+ "strings"++ "github.com/tracewayapp/traceway/backend/app/config"+)++func initTelemetryDB() error {+ if config.Config.DBType != "sqlite" {+ return nil+ }++ path := config.Config.SQLitePath+ if path == "" {+ path = "./traceway.db"+ }++ telemetryPath := strings.TrimSuffix(path, ".db") + "_telemetry.db"+ if path == ":memory:" {+ telemetryPath = ":memory:"+ }+ telDB, err := openSQLite(telemetryPath, true)+ if err != nil {+ return err+ }+ TelemetryDB = telDB+ config.Logf("SQLite telemetry database opened at %s", telemetryPath)++ return nil+}diff --git a/backend/app/db/db_transactional_pg.go b/backend/app/db/db_transactional_pg.gonew file mode 100644index 00000000..d7afcee8--- /dev/null+++ b/backend/app/db/db_transactional_pg.go@@ -0,0 +1,7 @@+//go:build transactional_pg++package db++func initMainDB() error {+ return initPostgres()+}diff --git a/backend/app/db/db_transactional_sqlite.go b/backend/app/db/db_transactional_sqlite.gonew file mode 100644index 00000000..3dbe4447--- /dev/null+++ b/backend/app/db/db_transactional_sqlite.go@@ -0,0 +1,29 @@+//go:build !transactional_pg++package db++import (+ "github.com/tracewayapp/lit/v2"+ "github.com/tracewayapp/traceway/backend/app/config"+)++func initMainDB() error {+ if config.Config.DBType != "sqlite" {+ return initPostgres()+ }++ path := config.Config.SQLitePath+ if path == "" {+ path = "./traceway.db"+ }++ mainDB, err := openSQLite(path, false)+ if err != nil {+ return err+ }+ DB = mainDB+ Driver = lit.SQLite+ config.Logf("SQLite database opened at %s", path)++ return nil+}diff --git a/backend/app/db/guard_ch_and_duckdb.go b/backend/app/db/guard_ch_and_duckdb.gonew file mode 100644index 00000000..c90d232f--- /dev/null+++ b/backend/app/db/guard_ch_and_duckdb.go@@ -0,0 +1,6 @@+//go:build telemetry_ch && telemetry_duckdb++package db++// The undefined identifier makes this unsupported tag combination fail at compile time.+var _ = build_error__telemetry_ch_and_telemetry_duckdb_are_mutually_exclusivediff --git a/backend/app/db/guard_ch_without_pg.go b/backend/app/db/guard_ch_without_pg.gonew file mode 100644index 00000000..bf0406b4--- /dev/null+++ b/backend/app/db/guard_ch_without_pg.go@@ -0,0 +1,6 @@+//go:build telemetry_ch && !transactional_pg++package db++// The undefined identifier makes this unsupported tag combination fail at compile time.+var _ = build_error__telemetry_ch_requires_transactional_pg__see_docs_learn_build_tagsdiff --git a/backend/app/db/guard_noop_tag_conflicts.go b/backend/app/db/guard_noop_tag_conflicts.gonew file mode 100644index 00000000..be2de51f--- /dev/null+++ b/backend/app/db/guard_noop_tag_conflicts.go@@ -0,0 +1,7 @@+//go:build (telemetry_sqlite && (telemetry_ch || telemetry_duckdb)) || (transactional_sqlite && transactional_pg)++package db++// telemetry_sqlite and transactional_sqlite are no-op tags (SQLite is the default); the+// undefined identifier rejects passing them together with a conflicting backend.+var _ = build_error__conflicting_backend_tags__sqlite_is_the_default_when_no_tag_is_setdiff --git a/backend/app/db/guard_pg_without_ch.go b/backend/app/db/guard_pg_without_ch.gonew file mode 100644index 00000000..59413647--- /dev/null+++ b/backend/app/db/guard_pg_without_ch.go@@ -0,0 +1,6 @@+//go:build transactional_pg && !telemetry_ch++package db++// The undefined identifier makes this unsupported tag combination fail at compile time.+var _ = build_error__transactional_pg_requires_telemetry_ch__see_docs_learn_build_tagsdiff --git a/backend/app/db/guard_stale_duckdb.go b/backend/app/db/guard_stale_duckdb.gonew file mode 100644index 00000000..1a431d99--- /dev/null+++ b/backend/app/db/guard_stale_duckdb.go@@ -0,0 +1,7 @@+//go:build duckdb++package db++// The duckdb tag was renamed; the undefined identifier fails the build so a stale+// invocation cannot silently produce the dual-SQLite binary.+var _ = build_error__tag_duckdb_was_renamed__use_telemetry_duckdbdiff --git a/backend/app/db/guard_stale_oltp.go b/backend/app/db/guard_stale_oltp.gonew file mode 100644index 00000000..4b32aff3--- /dev/null+++ b/backend/app/db/guard_stale_oltp.go@@ -0,0 +1,7 @@+//go:build oltp_pg || oltp_sqlite++package db++// The oltp_* axis was renamed; the undefined identifier fails the build so a+// stale invocation cannot silently produce the dual-SQLite binary.+var _ = build_error__oltp_tags_were_renamed__use_transactional_pg_and_transactional_sqlitediff --git a/backend/app/db/guard_stale_pgch.go b/backend/app/db/guard_stale_pgch.gonew file mode 100644index 00000000..a45e75b0--- /dev/null+++ b/backend/app/db/guard_stale_pgch.go@@ -0,0 +1,7 @@+//go:build pgch++package db++// The pgch tag was split into two axes; the undefined identifier fails the build+// so a stale invocation cannot silently produce the dual-SQLite binary.+var _ = build_error__tag_pgch_was_renamed__use_transactional_pg_and_telemetry_chdiff --git a/backend/app/db/telemetry_stats.go b/backend/app/db/telemetry_stats.gonew file mode 100644index 00000000..a020018f--- /dev/null+++ b/backend/app/db/telemetry_stats.go@@ -0,0 +1,63 @@+package db++import (+ "context"+ "sync"+)++type TelemetryEngineStats struct {+ DBSizeBytes int64 `json:"dbSizeBytes"`+ WALSizeBytes int64 `json:"walSizeBytes"`+ MemoryUsedBytes int64 `json:"memoryUsedBytes"`+ ReadPoolInUse int `json:"readPoolInUse"`+ ReadPoolWaitCount int64 `json:"readPoolWaitCount"`+ ReadPoolWaitMs int64 `json:"readPoolWaitMs"`+}++var telemetryEngineStatsFn func(context.Context) TelemetryEngineStats++func GetTelemetryEngineStats(ctx context.Context) (TelemetryEngineStats, bool) {+ if telemetryEngineStatsFn == nil {+ return TelemetryEngineStats{}, false+ }+ return telemetryEngineStatsFn(ctx), true+}++func TelemetryBackendName() string {+ if telemetryIsDuckDB {+ return "duckdb"+ }+ if TelemetryDB != nil {+ return "sqlite"+ }+ return "clickhouse"+}++var (+ telemetryIngestMu sync.Mutex+ telemetryDroppedRows = map[string]uint64{}+ telemetryInsertFailures uint64+)++func RecordTelemetryRowDropped(table string) {+ telemetryIngestMu.Lock()+ telemetryDroppedRows[table]+++ telemetryIngestMu.Unlock()+}++func RecordTelemetryInsertFailure() {+ telemetryIngestMu.Lock()+ telemetryInsertFailures+++ telemetryIngestMu.Unlock()+}++func GetTelemetryIngestCounters() (dropped map[string]uint64, droppedTotal uint64, insertFailures uint64) {+ telemetryIngestMu.Lock()+ defer telemetryIngestMu.Unlock()+ dropped = make(map[string]uint64, len(telemetryDroppedRows))+ for table, n := range telemetryDroppedRows {+ dropped[table] = n+ droppedTotal += n+ }+ return dropped, droppedTotal, telemetryInsertFailures+}diff --git a/backend/app/middleware/require_admin_access.middleware.go b/backend/app/middleware/require_admin_access.middleware.goindex 876277f1..43b3163a 100644--- a/backend/app/middleware/require_admin_access.middleware.go+++ b/backend/app/middleware/require_admin_access.middleware.go@@ -1,9 +1,9 @@package middlewareimport (- "github.com/tracewayapp/traceway/backend/app/db"- "github.com/tracewayapp/traceway/backend/app/repositories""database/sql"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional""net/http""strconv"@@ -32,7 +32,7 @@ func InitRequireAdminAccess() {}role, err := db.ExecuteTransaction(func(tx *sql.Tx) (string, error) {- return repositories.OrganizationRepository.GetUserRole(tx, organizationId, userId)+ return transactional.OrganizationRepository.GetUserRole(tx, organizationId, userId)})if err != nil {diff --git a/backend/app/middleware/require_project_access.middleware.go b/backend/app/middleware/require_project_access.middleware.goindex 179a6bc3..0c2ebb5b 100644--- a/backend/app/middleware/require_project_access.middleware.go+++ b/backend/app/middleware/require_project_access.middleware.go@@ -1,9 +1,9 @@package middlewareimport (- "github.com/tracewayapp/traceway/backend/app/db"- "github.com/tracewayapp/traceway/backend/app/repositories""database/sql"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional""net/http""github.com/gin-gonic/gin"@@ -31,7 +31,7 @@ func InitRequireProjectAccess() {}hasAccess, err := db.ExecuteTransaction(func(tx *sql.Tx) (bool, error) {- return repositories.ProjectRepository.UserHasAccess(tx, projectId, userId)+ return transactional.ProjectRepository.UserHasAccess(tx, projectId, userId)})if err != nil {diff --git a/backend/app/middleware/require_write_access.middleware.go b/backend/app/middleware/require_write_access.middleware.goindex 82a4df7d..ae8ec19a 100644--- a/backend/app/middleware/require_write_access.middleware.go+++ b/backend/app/middleware/require_write_access.middleware.go@@ -1,10 +1,10 @@package middlewareimport (+ "database/sql""github.com/tracewayapp/traceway/backend/app/cache""github.com/tracewayapp/traceway/backend/app/db"- "github.com/tracewayapp/traceway/backend/app/repositories"- "database/sql"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional""net/http""github.com/gin-gonic/gin"@@ -43,7 +43,7 @@ func InitRequireWriteAccess() {}role, err := db.ExecuteTransaction(func(tx *sql.Tx) (string, error) {- return repositories.OrganizationRepository.GetUserRole(tx, *project.OrganizationId, userId)+ return transactional.OrganizationRepository.GetUserRole(tx, *project.OrganizationId, userId)})if err != nil {diff --git a/backend/app/middleware/use_app_auth.middleware.go b/backend/app/middleware/use_app_auth.middleware.goindex e48c1246..b0a9627a 100644--- a/backend/app/middleware/use_app_auth.middleware.go+++ b/backend/app/middleware/use_app_auth.middleware.go@@ -8,7 +8,7 @@ import ("time""github.com/tracewayapp/traceway/backend/app/db"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional""github.com/tracewayapp/traceway/backend/app/services"traceway "go.tracewayapp.com"@@ -56,7 +56,7 @@ type BearerIdentity struct {func AuthenticateBearer(tokenString string) (*BearerIdentity, error) {if strings.HasPrefix(tokenString, "twp_") {- pat, err := repositories.PersonalAccessTokenRepository.FindActiveByToken(db.DB, tokenString)+ pat, err := transactional.PersonalAccessTokenRepository.FindActiveByToken(db.DB, tokenString)if err != nil {return nil, err}@@ -78,7 +78,7 @@ func AuthenticateBearer(tokenString string) (*BearerIdentity, error) {return identity, nil}-func touchPersonalAccessToken(pat *repositories.ActivePAT) {+func touchPersonalAccessToken(pat *transactional.ActivePAT) {now := time.Now()if pat.LastUsedAt != nil && now.Sub(*pat.LastUsedAt) < patTouchInterval {return@@ -87,7 +87,7 @@ func touchPersonalAccessToken(pat *repositories.ActivePAT) {go func() {defer traceway.Recover()_, _ = db.ExecuteTransaction(func(tx *sql.Tx) (struct{}, error) {- return struct{}{}, repositories.PersonalAccessTokenRepository.TouchLastUsed(tx, pat.Id, now)+ return struct{}{}, transactional.PersonalAccessTokenRepository.TouchLastUsed(tx, pat.Id, now)})}()}diff --git a/backend/app/migrations/duckdb_telemetry/0001_telemetry_tables.up.sql b/backend/app/migrations/duckdb_telemetry/0001_telemetry_tables.up.sqlnew file mode 100644index 00000000..65bd395a--- /dev/null+++ b/backend/app/migrations/duckdb_telemetry/0001_telemetry_tables.up.sql@@ -0,0 +1,220 @@+CREATE TABLE IF NOT EXISTS endpoints (+ id VARCHAR NOT NULL,+ project_id VARCHAR NOT NULL,+ endpoint VARCHAR NOT NULL DEFAULT '',+ duration BIGINT NOT NULL DEFAULT 0,+ recorded_at TIMESTAMP NOT NULL,+ status_code BIGINT NOT NULL DEFAULT 0,+ body_size BIGINT NOT NULL DEFAULT 0,+ client_ip VARCHAR NOT NULL DEFAULT '',+ attributes VARCHAR NOT NULL DEFAULT '{}',+ app_version VARCHAR NOT NULL DEFAULT '',+ server_name VARCHAR NOT NULL DEFAULT '',+ distributed_trace_id VARCHAR,+ span_id VARCHAR,+ is_stream BIGINT NOT NULL DEFAULT 0,+ is_root BIGINT NOT NULL DEFAULT 1+);++CREATE TABLE IF NOT EXISTS tasks (+ id VARCHAR NOT NULL,+ project_id VARCHAR NOT NULL,+ task_name VARCHAR NOT NULL DEFAULT '',+ duration BIGINT NOT NULL DEFAULT 0,+ recorded_at TIMESTAMP NOT NULL,+ client_ip VARCHAR NOT NULL DEFAULT '',+ attributes VARCHAR NOT NULL DEFAULT '{}',+ app_version VARCHAR NOT NULL DEFAULT '',+ server_name VARCHAR NOT NULL DEFAULT '',+ distributed_trace_id VARCHAR,+ span_id VARCHAR,+ is_root BIGINT NOT NULL DEFAULT 1+);++CREATE TABLE IF NOT EXISTS exception_stack_traces (+ id VARCHAR NOT NULL,+ project_id VARCHAR NOT NULL,+ trace_id VARCHAR,+ trace_type VARCHAR NOT NULL DEFAULT 'endpoint',+ exception_hash VARCHAR NOT NULL DEFAULT '',+ stack_trace VARCHAR NOT NULL DEFAULT '',+ recorded_at TIMESTAMP NOT NULL,+ attributes VARCHAR NOT NULL DEFAULT '{}',+ app_version VARCHAR NOT NULL DEFAULT '',+ server_name VARCHAR NOT NULL DEFAULT '',+ is_message BIGINT NOT NULL DEFAULT 0,+ distributed_trace_id VARCHAR,+ session_id VARCHAR+);++CREATE TABLE IF NOT EXISTS spans (+ id VARCHAR NOT NULL,+ trace_id VARCHAR NOT NULL,+ project_id VARCHAR NOT NULL,+ name VARCHAR NOT NULL DEFAULT '',+ start_time TIMESTAMP NOT NULL,+ duration BIGINT NOT NULL DEFAULT 0,+ recorded_at TIMESTAMP NOT NULL,+ parent_span_id VARCHAR,+ attributes VARCHAR NOT NULL DEFAULT '{}'+);++CREATE TABLE IF NOT EXISTS metric_points (+ project_id VARCHAR NOT NULL,+ name VARCHAR NOT NULL DEFAULT '',+ value DOUBLE NOT NULL DEFAULT 0,+ tags VARCHAR NOT NULL DEFAULT '{}',+ recorded_at TIMESTAMP NOT NULL,+ server_name VARCHAR NOT NULL DEFAULT ''+);++CREATE TABLE IF NOT EXISTS session_recordings (+ id VARCHAR NOT NULL,+ project_id VARCHAR NOT NULL,+ exception_id VARCHAR NOT NULL,+ file_path VARCHAR NOT NULL DEFAULT '',+ recorded_at TIMESTAMP NOT NULL,+ session_id VARCHAR,+ segment_index BIGINT NOT NULL DEFAULT 0+);++CREATE TABLE IF NOT EXISTS archived_exceptions (+ project_id VARCHAR NOT NULL,+ exception_hash VARCHAR NOT NULL,+ archived_at TIMESTAMP NOT NULL DEFAULT now(),+ UNIQUE(project_id, exception_hash)+);++CREATE TABLE IF NOT EXISTS slow_endpoints (+ project_id VARCHAR NOT NULL,+ endpoint VARCHAR NOT NULL,+ offset_ms BIGINT NOT NULL DEFAULT 0,+ reason VARCHAR NOT NULL DEFAULT '',+ UNIQUE(project_id, endpoint)+);++CREATE TABLE IF NOT EXISTS fired_notifications (+ project_id VARCHAR NOT NULL,+ rule_id BIGINT NOT NULL DEFAULT 0,+ rule_type VARCHAR NOT NULL DEFAULT '',+ rule_name VARCHAR NOT NULL DEFAULT '',+ channel_type VARCHAR NOT NULL DEFAULT '',+ channel_name VARCHAR NOT NULL DEFAULT '',+ severity VARCHAR NOT NULL DEFAULT '',+ subject VARCHAR NOT NULL DEFAULT '',+ body VARCHAR NOT NULL DEFAULT '',+ status VARCHAR NOT NULL DEFAULT '',+ error_message VARCHAR NOT NULL DEFAULT '',+ endpoint VARCHAR NOT NULL DEFAULT '',+ fired_at TIMESTAMP NOT NULL,+ url VARCHAR NOT NULL DEFAULT ''+);++CREATE TABLE IF NOT EXISTS ai_traces (+ id VARCHAR NOT NULL,+ project_id VARCHAR NOT NULL,+ recorded_at TIMESTAMP NOT NULL,+ duration BIGINT NOT NULL DEFAULT 0,+ status_code BIGINT NOT NULL DEFAULT 0,+ model VARCHAR NOT NULL DEFAULT '',+ response_model VARCHAR NOT NULL DEFAULT '',+ provider VARCHAR NOT NULL DEFAULT '',+ operation VARCHAR NOT NULL DEFAULT '',+ input_tokens BIGINT NOT NULL DEFAULT 0,+ output_tokens BIGINT NOT NULL DEFAULT 0,+ total_tokens BIGINT NOT NULL DEFAULT 0,+ cached_tokens BIGINT NOT NULL DEFAULT 0,+ reasoning_tokens BIGINT NOT NULL DEFAULT 0,+ input_cost DOUBLE NOT NULL DEFAULT 0,+ output_cost DOUBLE NOT NULL DEFAULT 0,+ total_cost DOUBLE NOT NULL DEFAULT 0,+ trace_name VARCHAR NOT NULL DEFAULT '',+ user_id VARCHAR NOT NULL DEFAULT '',+ finish_reason VARCHAR NOT NULL DEFAULT '',+ server_name VARCHAR NOT NULL DEFAULT '',+ app_version VARCHAR NOT NULL DEFAULT '',+ storage_key VARCHAR NOT NULL DEFAULT '',+ attributes VARCHAR NOT NULL DEFAULT '{}',+ is_root BIGINT NOT NULL DEFAULT 1,+ distributed_trace_id VARCHAR+);++CREATE TABLE IF NOT EXISTS log_records (+ id VARCHAR NOT NULL,+ project_id VARCHAR NOT NULL,+ timestamp TIMESTAMP NOT NULL,+ trace_id VARCHAR NOT NULL DEFAULT '',+ span_id VARCHAR NOT NULL DEFAULT '',+ trace_flags BIGINT NOT NULL DEFAULT 0,+ severity_text VARCHAR NOT NULL DEFAULT '',+ severity_number BIGINT NOT NULL DEFAULT 0,+ service_name VARCHAR NOT NULL DEFAULT '',+ body VARCHAR NOT NULL DEFAULT '',+ resource_schema_url VARCHAR NOT NULL DEFAULT '',+ resource_attributes VARCHAR NOT NULL DEFAULT '{}',+ scope_schema_url VARCHAR NOT NULL DEFAULT '',+ scope_name VARCHAR NOT NULL DEFAULT '',+ scope_version VARCHAR NOT NULL DEFAULT '',+ scope_attributes VARCHAR NOT NULL DEFAULT '{}',+ log_attributes VARCHAR NOT NULL DEFAULT '{}'+);++CREATE TABLE IF NOT EXISTS sessions (+ id VARCHAR NOT NULL PRIMARY KEY,+ project_id VARCHAR NOT NULL,+ started_at TIMESTAMP NOT NULL,+ ended_at TIMESTAMP,+ duration BIGINT NOT NULL DEFAULT 0,+ client_ip VARCHAR NOT NULL DEFAULT '',+ attributes VARCHAR NOT NULL DEFAULT '{}',+ app_version VARCHAR NOT NULL DEFAULT '',+ server_name VARCHAR NOT NULL DEFAULT '',+ distributed_trace_id VARCHAR+);++CREATE TABLE IF NOT EXISTS profiling_stacks (+ project_id VARCHAR NOT NULL,+ service_name VARCHAR NOT NULL DEFAULT '',+ stack_hash BIGINT NOT NULL,+ stack VARCHAR NOT NULL DEFAULT '[]',+ last_seen TIMESTAMP NOT NULL,+ UNIQUE(project_id, service_name, stack_hash)+);++CREATE TABLE IF NOT EXISTS profiling_samples (+ project_id VARCHAR NOT NULL,+ profile_id VARCHAR NOT NULL,+ service_name VARCHAR NOT NULL DEFAULT '',+ type VARCHAR NOT NULL DEFAULT '',+ start_time TIMESTAMP NOT NULL,+ end_time TIMESTAMP NOT NULL,+ stack_hash BIGINT NOT NULL,+ value BIGINT NOT NULL DEFAULT 0,+ labels VARCHAR NOT NULL DEFAULT '{}',+ server_name VARCHAR NOT NULL DEFAULT '',+ app_version VARCHAR NOT NULL DEFAULT '',+ trace_id VARCHAR NOT NULL DEFAULT '',+ span_id VARCHAR NOT NULL DEFAULT '',+ unit VARCHAR NOT NULL DEFAULT '',+ is_gauge BIGINT NOT NULL DEFAULT 0+);++CREATE TABLE IF NOT EXISTS profiles (+ id VARCHAR NOT NULL,+ project_id VARCHAR NOT NULL,+ recorded_at TIMESTAMP NOT NULL,+ duration BIGINT NOT NULL DEFAULT 0,+ service_name VARCHAR NOT NULL DEFAULT '',+ profile_type VARCHAR NOT NULL DEFAULT '',+ sample_count BIGINT NOT NULL DEFAULT 0,+ total_value BIGINT NOT NULL DEFAULT 0,+ server_name VARCHAR NOT NULL DEFAULT '',+ app_version VARCHAR NOT NULL DEFAULT '',+ attributes VARCHAR NOT NULL DEFAULT '{}',+ storage_key VARCHAR NOT NULL DEFAULT '',+ trace_id VARCHAR NOT NULL DEFAULT '',+ span_id VARCHAR NOT NULL DEFAULT '',+ distributed_trace_id VARCHAR,+ unit VARCHAR NOT NULL DEFAULT '',+ is_gauge BIGINT NOT NULL DEFAULT 0+);diff --git a/backend/app/migrations/migrations_sqlite.go b/backend/app/migrations/migrations.gosimilarity index 67%rename from backend/app/migrations/migrations_sqlite.gorename to backend/app/migrations/migrations.goindex 6496c87d..99f1631b 100644--- a/backend/app/migrations/migrations_sqlite.go+++ b/backend/app/migrations/migrations.go@@ -1,5 +1,3 @@-//go:build !pgch-package migrationsimport (@@ -8,8 +6,6 @@ import ("fmt""sort""strings"-- "github.com/tracewayapp/traceway/backend/app/db")type ExtensionMigration struct {@@ -23,27 +19,13 @@ var ExtensionPostgresMigrations []ExtensionMigration//go:embed sqlite/*.sqlvar migrationsSqliteFS embed.FS-//go:embed sqlite_telemetry/*.sql-var migrationsSqliteTelemetryFS embed.FS--func Run(dbType string) error {- if err := runMigrationsOn(db.DB, migrationsSqliteFS, "sqlite", "schema_migrations"); err != nil {- return fmt.Errorf("main db migrations: %w", err)- }-- if err := runMigrationsOn(db.TelemetryDB, migrationsSqliteTelemetryFS, "sqlite_telemetry", "schema_migrations"); err != nil {- return fmt.Errorf("telemetry db migrations: %w", err)- }+const sqliteTrackingDDL = `CREATE TABLE IF NOT EXISTS %s (+ version TEXT PRIMARY KEY,+ applied_at DATETIME DEFAULT (datetime('now'))+)`- return nil-}--func runMigrationsOn(target *sql.DB, fsys embed.FS, dir string, trackingTable string) error {- _, err := target.Exec(fmt.Sprintf(`CREATE TABLE IF NOT EXISTS %s (- version TEXT PRIMARY KEY,- applied_at DATETIME DEFAULT (datetime('now'))- )`, trackingTable))- if err != nil {+func runMigrationsOn(target *sql.DB, fsys embed.FS, dir, trackingTable, createTrackingSQL string) error {+ if _, err := target.Exec(fmt.Sprintf(createTrackingSQL, trackingTable)); err != nil {return fmt.Errorf("failed to create %s table: %w", trackingTable, err)}diff --git a/backend/app/migrations/migrations_default.go b/backend/app/migrations/migrations_default.godeleted file mode 100644index 5889e708..00000000--- a/backend/app/migrations/migrations_default.go+++ /dev/null@@ -1,235 +0,0 @@-//go:build pgch--package migrations--import (- "database/sql"- "embed"- "fmt"- "net/url"- "sort"- "strings"-- "github.com/tracewayapp/traceway/backend/app/config"- "github.com/tracewayapp/traceway/backend/app/db"-- "github.com/golang-migrate/migrate/v4"- migrateCh "github.com/golang-migrate/migrate/v4/database/clickhouse"- migratePg "github.com/golang-migrate/migrate/v4/database/postgres"- "github.com/golang-migrate/migrate/v4/source/iofs"- _ "github.com/lib/pq"-)--type ExtensionMigration struct {- Source embed.FS- Path string- Table string // unique migration table name per extension-}--var ExtensionPostgresMigrations []ExtensionMigration--//go:embed ch/*.sql-var migrationsChFS embed.FS--//go:embed pg/*.sql-var migrationsPgFS embed.FS--//go:embed sqlite/*.sql-var migrationsSqliteFS embed.FS--func runMigrationsClickhouse(connStr string) error {- db, err := sql.Open("clickhouse", connStr)- if err != nil {- return err- }- defer db.Close()-- source, err := iofs.New(migrationsChFS, "ch")- if err != nil {- return err- }-- driver, err := migrateCh.WithInstance(db, &migrateCh.Config{- MigrationsTableEngine: "MergeTree",- })- if err != nil {- return err- }-- m, err := migrate.NewWithInstance("iofs", source, "clickhouse", driver)- if err != nil {- return err- }-- if err := m.Up(); err != nil && err != migrate.ErrNoChange {- return err- }-- return nil-}--func runMigrationsPostgres(connStr string) error {- db, err := sql.Open("postgres", connStr)- if err != nil {- return fmt.Errorf("failed to open postgres for migrations: %w", err)- }- defer db.Close()-- source, err := iofs.New(migrationsPgFS, "pg")- if err != nil {- return fmt.Errorf("failed to create migration source: %w", err)- }-- driver, err := migratePg.WithInstance(db, &migratePg.Config{})- if err != nil {- return fmt.Errorf("failed to create migration driver: %w", err)- }-- m, err := migrate.NewWithInstance("iofs", source, "postgres", driver)- if err != nil {- return fmt.Errorf("failed to create migrate instance: %w", err)- }-- if err := m.Up(); err != nil && err != migrate.ErrNoChange {- return fmt.Errorf("postgres migration failed: %w", err)- }-- for _, ext := range ExtensionPostgresMigrations {- if err := runExtensionMigrations(db, ext); err != nil {- return fmt.Errorf("extension migration failed: %w", err)- }- }-- return nil-}--func runExtensionMigrations(db *sql.DB, ext ExtensionMigration) error {- source, err := iofs.New(ext.Source, ext.Path)- if err != nil {- return fmt.Errorf("failed to create extension migration source: %w", err)- }-- tableName := ext.Table- if tableName == "" {- tableName = "schema_migrations_ext"- }-- driver, err := migratePg.WithInstance(db, &migratePg.Config{- MigrationsTable: tableName,- })- if err != nil {- return fmt.Errorf("failed to create extension migration driver: %w", err)- }-- m, err := migrate.NewWithInstance("iofs", source, "postgres", driver)- if err != nil {- return fmt.Errorf("failed to create extension migrate instance: %w", err)- }-- if err := m.Up(); err != nil && err != migrate.ErrNoChange {- return fmt.Errorf("extension postgres migration failed: %w", err)- }-- return nil-}--func runMigrationsSQLite(db *sql.DB) error {- _, err := db.Exec(`CREATE TABLE IF NOT EXISTS schema_migrations (- version TEXT PRIMARY KEY,- applied_at DATETIME DEFAULT (datetime('now'))- )`)- if err != nil {- return fmt.Errorf("failed to create schema_migrations table: %w", err)- }-- entries, err := migrationsSqliteFS.ReadDir("sqlite")- if err != nil {- return fmt.Errorf("failed to read sqlite migrations dir: %w", err)- }-- var files []string- for _, e := range entries {- if !e.IsDir() && strings.HasSuffix(e.Name(), ".up.sql") {- files = append(files, e.Name())- }- }- sort.Strings(files)-- for _, file := range files {- version := strings.TrimSuffix(file, ".up.sql")-- var count int- err := db.QueryRow("SELECT COUNT(*) FROM schema_migrations WHERE version = ?", version).Scan(&count)- if err != nil {- return fmt.Errorf("failed to check migration version %s: %w", version, err)- }- if count > 0 {- continue- }-- content, err := migrationsSqliteFS.ReadFile("sqlite/" + file)- if err != nil {- return fmt.Errorf("failed to read migration file %s: %w", file, err)- }-- statements := strings.Split(string(content), ";")- for _, stmt := range statements {- stmt = strings.TrimSpace(stmt)- if stmt == "" {- continue- }- if _, err := db.Exec(stmt); err != nil {- return fmt.Errorf("failed to execute migration %s: %w", file, err)- }- }-- if _, err := db.Exec("INSERT INTO schema_migrations (version) VALUES (?)", version); err != nil {- return fmt.Errorf("failed to record migration version %s: %w", version, err)- }- }-- return nil-}--func Run(dbType string) error {- cfg := config.Config-- // Run ClickHouse migrations- tlsConfig := "&secure=true"- if cfg.ClickhouseTLS == "false" {- tlsConfig = ""- }-- err := runMigrationsClickhouse(fmt.Sprintf(`clickhouse://%s?username=%s&password=%s&database=%s%s`, cfg.ClickhouseServer, url.QueryEscape(cfg.ClickhouseUsername), url.QueryEscape(cfg.ClickhousePassword), cfg.ClickhouseDatabase, tlsConfig))- if err != nil {- return fmt.Errorf("clickhouse migrations failed: %w", err)- }-- if dbType == "sqlite" {- if err := runMigrationsSQLite(db.DB); err != nil {- return fmt.Errorf("sqlite migrations failed: %w", err)- }-- return nil- }-- // Run PostgreSQL migrations- pgPort := cfg.PostgresPort- pgSSLMode := cfg.PostgresSSLMode-- if pgSSLMode == "" {- pgSSLMode = "disable"- }- if pgPort == "" {- pgPort = "5432"- }-- pgConnStr := fmt.Sprintf("postgres://%s:%s@%s:%s/%s?sslmode=%s",- url.QueryEscape(cfg.PostgresUsername), url.QueryEscape(cfg.PostgresPassword), cfg.PostgresHost, pgPort, cfg.PostgresDatabase, pgSSLMode)-- if err := runMigrationsPostgres(pgConnStr); err != nil {- return fmt.Errorf("postgres migrations failed: %w", err)- }-- return nil-}diff --git a/backend/app/migrations/migrations_telemetry_ch.go b/backend/app/migrations/migrations_telemetry_ch.gonew file mode 100644index 00000000..103e4233--- /dev/null+++ b/backend/app/migrations/migrations_telemetry_ch.go@@ -0,0 +1,66 @@+//go:build telemetry_ch++package migrations++import (+ "database/sql"+ "embed"+ "fmt"+ "net/url"++ "github.com/tracewayapp/traceway/backend/app/config"++ "github.com/golang-migrate/migrate/v4"+ migrateCh "github.com/golang-migrate/migrate/v4/database/clickhouse"+ "github.com/golang-migrate/migrate/v4/source/iofs"+)++//go:embed ch/*.sql+var migrationsChFS embed.FS++func runMigrationsClickhouse(connStr string) error {+ db, err := sql.Open("clickhouse", connStr)+ if err != nil {+ return err+ }+ defer db.Close()++ source, err := iofs.New(migrationsChFS, "ch")+ if err != nil {+ return err+ }++ driver, err := migrateCh.WithInstance(db, &migrateCh.Config{+ MigrationsTableEngine: "MergeTree",+ })+ if err != nil {+ return err+ }++ m, err := migrate.NewWithInstance("iofs", source, "clickhouse", driver)+ if err != nil {+ return err+ }++ if err := m.Up(); err != nil && err != migrate.ErrNoChange {+ return err+ }++ return nil+}++func Run(dbType string) error {+ cfg := config.Config++ tlsConfig := "&secure=true"+ if cfg.ClickhouseTLS == "false" {+ tlsConfig = ""+ }++ err := runMigrationsClickhouse(fmt.Sprintf(`clickhouse://%s?username=%s&password=%s&database=%s%s`, cfg.ClickhouseServer, url.QueryEscape(cfg.ClickhouseUsername), url.QueryEscape(cfg.ClickhousePassword), cfg.ClickhouseDatabase, tlsConfig))+ if err != nil {+ return fmt.Errorf("clickhouse migrations failed: %w", err)+ }++ return runMainDBMigrations(dbType)+}diff --git a/backend/app/migrations/migrations_telemetry_duckdb.go b/backend/app/migrations/migrations_telemetry_duckdb.gonew file mode 100644index 00000000..b91450ea--- /dev/null+++ b/backend/app/migrations/migrations_telemetry_duckdb.go@@ -0,0 +1,30 @@+//go:build telemetry_duckdb++package migrations++import (+ "embed"+ "fmt"++ "github.com/tracewayapp/traceway/backend/app/db"+)++//go:embed duckdb_telemetry/*.sql+var migrationsDuckDBTelemetryFS embed.FS++const duckdbTrackingDDL = `CREATE TABLE IF NOT EXISTS %s (+ version VARCHAR PRIMARY KEY,+ applied_at TIMESTAMP DEFAULT now()+)`++func Run(dbType string) error {+ if err := runMainDBMigrations(dbType); err != nil {+ return err+ }++ if err := runMigrationsOn(db.TelemetryDB, migrationsDuckDBTelemetryFS, "duckdb_telemetry", "schema_migrations", duckdbTrackingDDL); err != nil {+ return fmt.Errorf("telemetry db migrations: %w", err)+ }++ return nil+}diff --git a/backend/app/migrations/migrations_telemetry_sqlite.go b/backend/app/migrations/migrations_telemetry_sqlite.gonew file mode 100644index 00000000..a046433b--- /dev/null+++ b/backend/app/migrations/migrations_telemetry_sqlite.go@@ -0,0 +1,25 @@+//go:build !telemetry_ch && !telemetry_duckdb++package migrations++import (+ "embed"+ "fmt"++ "github.com/tracewayapp/traceway/backend/app/db"+)++//go:embed sqlite_telemetry/*.sql+var migrationsSqliteTelemetryFS embed.FS++func Run(dbType string) error {+ if err := runMainDBMigrations(dbType); err != nil {+ return err+ }++ if err := runMigrationsOn(db.TelemetryDB, migrationsSqliteTelemetryFS, "sqlite_telemetry", "schema_migrations", sqliteTrackingDDL); err != nil {+ return fmt.Errorf("telemetry db migrations: %w", err)+ }++ return nil+}diff --git a/backend/app/migrations/migrations_transactional_pg.go b/backend/app/migrations/migrations_transactional_pg.gonew file mode 100644index 00000000..67a38fd9--- /dev/null+++ b/backend/app/migrations/migrations_transactional_pg.go@@ -0,0 +1,116 @@+//go:build transactional_pg++package migrations++import (+ "database/sql"+ "embed"+ "fmt"+ "net/url"++ "github.com/tracewayapp/traceway/backend/app/config"+ "github.com/tracewayapp/traceway/backend/app/db"++ "github.com/golang-migrate/migrate/v4"+ migratePg "github.com/golang-migrate/migrate/v4/database/postgres"+ "github.com/golang-migrate/migrate/v4/source/iofs"+ _ "github.com/lib/pq"+)++//go:embed pg/*.sql+var migrationsPgFS embed.FS++func runMigrationsPostgres(connStr string) error {+ db, err := sql.Open("postgres", connStr)+ if err != nil {+ return fmt.Errorf("failed to open postgres for migrations: %w", err)+ }+ defer db.Close()++ source, err := iofs.New(migrationsPgFS, "pg")+ if err != nil {+ return fmt.Errorf("failed to create migration source: %w", err)+ }++ driver, err := migratePg.WithInstance(db, &migratePg.Config{})+ if err != nil {+ return fmt.Errorf("failed to create migration driver: %w", err)+ }++ m, err := migrate.NewWithInstance("iofs", source, "postgres", driver)+ if err != nil {+ return fmt.Errorf("failed to create migrate instance: %w", err)+ }++ if err := m.Up(); err != nil && err != migrate.ErrNoChange {+ return fmt.Errorf("postgres migration failed: %w", err)+ }++ for _, ext := range ExtensionPostgresMigrations {+ if err := runExtensionMigrations(db, ext); err != nil {+ return fmt.Errorf("extension migration failed: %w", err)+ }+ }++ return nil+}++func runExtensionMigrations(db *sql.DB, ext ExtensionMigration) error {+ source, err := iofs.New(ext.Source, ext.Path)+ if err != nil {+ return fmt.Errorf("failed to create extension migration source: %w", err)+ }++ tableName := ext.Table+ if tableName == "" {+ tableName = "schema_migrations_ext"+ }++ driver, err := migratePg.WithInstance(db, &migratePg.Config{+ MigrationsTable: tableName,+ })+ if err != nil {+ return fmt.Errorf("failed to create extension migration driver: %w", err)+ }++ m, err := migrate.NewWithInstance("iofs", source, "postgres", driver)+ if err != nil {+ return fmt.Errorf("failed to create extension migrate instance: %w", err)+ }++ if err := m.Up(); err != nil && err != migrate.ErrNoChange {+ return fmt.Errorf("extension postgres migration failed: %w", err)+ }++ return nil+}++func runMainDBMigrations(dbType string) error {+ if dbType == "sqlite" {+ if err := runMigrationsOn(db.DB, migrationsSqliteFS, "sqlite", "schema_migrations", sqliteTrackingDDL); err != nil {+ return fmt.Errorf("sqlite migrations failed: %w", err)+ }+ return nil+ }++ cfg := config.Config++ pgPort := cfg.PostgresPort+ pgSSLMode := cfg.PostgresSSLMode++ if pgSSLMode == "" {+ pgSSLMode = "disable"+ }+ if pgPort == "" {+ pgPort = "5432"+ }++ pgConnStr := fmt.Sprintf("postgres://%s:%s@%s:%s/%s?sslmode=%s",+ url.QueryEscape(cfg.PostgresUsername), url.QueryEscape(cfg.PostgresPassword), cfg.PostgresHost, pgPort, cfg.PostgresDatabase, pgSSLMode)++ if err := runMigrationsPostgres(pgConnStr); err != nil {+ return fmt.Errorf("postgres migrations failed: %w", err)+ }++ return nil+}diff --git a/backend/app/migrations/migrations_transactional_sqlite.go b/backend/app/migrations/migrations_transactional_sqlite.gonew file mode 100644index 00000000..217d41ba--- /dev/null+++ b/backend/app/migrations/migrations_transactional_sqlite.go@@ -0,0 +1,16 @@+//go:build !transactional_pg++package migrations++import (+ "fmt"++ "github.com/tracewayapp/traceway/backend/app/db"+)++func runMainDBMigrations(_ string) error {+ if err := runMigrationsOn(db.DB, migrationsSqliteFS, "sqlite", "schema_migrations", sqliteTrackingDDL); err != nil {+ return fmt.Errorf("main db migrations: %w", err)+ }+ return nil+}diff --git a/backend/app/monitoring/backend_reporter.go b/backend/app/monitoring/backend_reporter.goindex 57b924b3..30d7b8dc 100644--- a/backend/app/monitoring/backend_reporter.go+++ b/backend/app/monitoring/backend_reporter.go@@ -7,7 +7,7 @@ import (traceway "go.tracewayapp.com""github.com/tracewayapp/traceway/backend/app/cache"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional""github.com/tracewayapp/traceway/backend/app/services")@@ -94,7 +94,7 @@ func reportBackendOnce(b *backendBaselines) {b.first = falsetraceway.CaptureMetric("traceway.cache.projects.entries", float64(cache.ProjectCache.Entries()))- traceway.CaptureMetric("traceway.cache.metric_registry.entries", float64(repositories.MetricRegistryRepository.KnownCount()))+ traceway.CaptureMetric("traceway.cache.metric_registry.entries", float64(transactional.MetricRegistryRepository.KnownCount()))}// Guards against counter resets across process/CH restart producing a hugediff --git a/backend/app/monitoring/ch_reporter.go b/backend/app/monitoring/ch_reporter.goindex b0c28311..ed977814 100644--- a/backend/app/monitoring/ch_reporter.go+++ b/backend/app/monitoring/ch_reporter.go@@ -1,4 +1,4 @@-//go:build pgch+//go:build telemetry_chpackage monitoringdiff --git a/backend/app/monitoring/ch_reporter_sqlite.go b/backend/app/monitoring/ch_reporter_sqlite.goindex dedd7814..432049b7 100644--- a/backend/app/monitoring/ch_reporter_sqlite.go+++ b/backend/app/monitoring/ch_reporter_sqlite.go@@ -1,4 +1,4 @@-//go:build !pgch+//go:build !telemetry_chpackage monitoringdiff --git a/backend/app/monitoring/telemetrydb_reporter.go b/backend/app/monitoring/telemetrydb_reporter.gonew file mode 100644index 00000000..cc4b0419--- /dev/null+++ b/backend/app/monitoring/telemetrydb_reporter.go@@ -0,0 +1,77 @@+package monitoring++import (+ "context"+ "time"++ traceway "go.tracewayapp.com"++ "github.com/tracewayapp/traceway/backend/app/db"+)++const telemetryDBReportInterval = 10 * time.Second++type telemetryDBBaselines struct {+ dropped uint64+ insertFailures uint64+ poolWaitCount int64+ poolWaitMs int64+ first bool+}++func StartTelemetryDBReporter(ctx context.Context) {+ if !db.IsDuckDBTelemetry() {+ return+ }+ go func() {+ defer traceway.Recover()++ ticker := time.NewTicker(telemetryDBReportInterval)+ defer ticker.Stop()++ baselines := &telemetryDBBaselines{first: true}++ reportTelemetryDBOnce(ctx, baselines)++ for {+ select {+ case <-ctx.Done():+ return+ case <-ticker.C:+ reportTelemetryDBOnce(ctx, baselines)+ }+ }+ }()+}++func reportTelemetryDBOnce(ctx context.Context, b *telemetryDBBaselines) {+ _, droppedTotal, insertFailures := db.GetTelemetryIngestCounters()+ engine, ok := db.GetTelemetryEngineStats(ctx)+ if !ok {+ return+ }++ if !b.first {+ traceway.CaptureMetric("traceway.duckdb.rows_dropped.delta", float64(safeDelta(b.dropped, droppedTotal)))+ traceway.CaptureMetric("traceway.duckdb.insert_failures.delta", float64(safeDelta(b.insertFailures, insertFailures)))+ traceway.CaptureMetric("traceway.duckdb.read_pool.wait_count.delta", float64(safeDeltaInt64(b.poolWaitCount, engine.ReadPoolWaitCount)))+ traceway.CaptureMetric("traceway.duckdb.read_pool.wait_ms.delta", float64(safeDeltaInt64(b.poolWaitMs, engine.ReadPoolWaitMs)))+ }+ b.dropped = droppedTotal+ b.insertFailures = insertFailures+ b.poolWaitCount = engine.ReadPoolWaitCount+ b.poolWaitMs = engine.ReadPoolWaitMs+ b.first = false++ traceway.CaptureMetric("traceway.duckdb.db_size_mb", float64(engine.DBSizeBytes)/1024.0/1024.0)+ traceway.CaptureMetric("traceway.duckdb.wal_size_mb", float64(engine.WALSizeBytes)/1024.0/1024.0)+ traceway.CaptureMetric("traceway.duckdb.memory_used_mb", float64(engine.MemoryUsedBytes)/1024.0/1024.0)+ traceway.CaptureMetric("traceway.duckdb.read_pool.in_use", float64(engine.ReadPoolInUse))+}++func safeDeltaInt64(prev, cur int64) int64 {+ if cur < prev {+ return cur+ }+ return cur - prev+}diff --git a/backend/app/notifications/dispatch.go b/backend/app/notifications/dispatch.goindex 1a8dc5a5..c02e5554 100644--- a/backend/app/notifications/dispatch.go+++ b/backend/app/notifications/dispatch.go@@ -10,7 +10,8 @@ import ("github.com/tracewayapp/traceway/backend/app/db""github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional"traceway "go.tracewayapp.com")@@ -24,7 +25,7 @@ func sanitizeForDB(s string) string {func dispatch(rule *models.NotificationRuleWithChannel, msg Message) {channel, dbErr := db.ExecuteTransaction(func(tx *sql.Tx) (*models.NotificationChannel, error) {- return repositories.NotificationChannelRepository.FindById(tx, rule.ChannelId)+ return transactional.NotificationChannelRepository.FindById(tx, rule.ChannelId)})if dbErr != nil || channel == nil {recordFiredNotification(rule, msg, "failed", "failed to load channel")@@ -61,7 +62,7 @@ func recordFiredNotification(rule *models.NotificationRuleWithChannel, msg Messago func() {defer traceway.Recover()- err := repositories.FiredNotificationRepository.Insert(context.Background(), repositories.FiredNotification{+ err := telemetry.FiredNotificationRepository.Insert(context.Background(), telemetry.FiredNotification{ProjectId: rule.ProjectId,RuleId: rule.Id,RuleType: rule.RuleType,@@ -82,4 +83,3 @@ func recordFiredNotification(rule *models.NotificationRuleWithChannel, msg Messa}}()}-diff --git a/backend/app/notifications/evaluator.go b/backend/app/notifications/evaluator.goindex 4b7a1f48..2257ab41 100644--- a/backend/app/notifications/evaluator.go+++ b/backend/app/notifications/evaluator.go@@ -10,7 +10,8 @@ import ("github.com/tracewayapp/traceway/backend/app/config""github.com/tracewayapp/traceway/backend/app/db""github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional"traceway "go.tracewayapp.com")@@ -33,7 +34,7 @@ func pollInterval() time.Duration {}func seedCooldowns(ctx context.Context) {- entries, err := repositories.FiredNotificationRepository.FindLastFiredPerRule(ctx)+ entries, err := telemetry.FiredNotificationRepository.FindLastFiredPerRule(ctx)if err != nil {traceway.CaptureException(fmt.Errorf("failed to seed notification cooldowns: %w", err))return@@ -59,7 +60,7 @@ func startPolledLoop(ctx context.Context) {func evaluatePolledRules(ctx context.Context) {rules, err := db.ExecuteTransaction(func(tx *sql.Tx) ([]*models.NotificationRuleWithChannel, error) {- return repositories.NotificationRuleRepository.FindEnabledPolledRules(tx)+ return transactional.NotificationRuleRepository.FindEnabledPolledRules(tx)})if err != nil {traceway.CaptureException(fmt.Errorf("failed to load polled notification rules: %w", err))diff --git a/backend/app/notifications/evaluator_event.go b/backend/app/notifications/evaluator_event.goindex b9eb294e..ca23ee8b 100644--- a/backend/app/notifications/evaluator_event.go+++ b/backend/app/notifications/evaluator_event.go@@ -1,4 +1,4 @@-//go:build pgch+//go:build telemetry_chpackage notificationsdiff --git a/backend/app/notifications/evaluator_event_sqlite.go b/backend/app/notifications/evaluator_event_sqlite.goindex f278dd37..513ad09d 100644--- a/backend/app/notifications/evaluator_event_sqlite.go+++ b/backend/app/notifications/evaluator_event_sqlite.go@@ -1,4 +1,4 @@-//go:build !pgch+//go:build !telemetry_chpackage notificationsdiff --git a/backend/app/notifications/evaluator_helpers.go b/backend/app/notifications/evaluator_helpers.goindex c71ef783..bae95702 100644--- a/backend/app/notifications/evaluator_helpers.go+++ b/backend/app/notifications/evaluator_helpers.go@@ -12,7 +12,8 @@ import ("github.com/tracewayapp/traceway/backend/app/db""github.com/tracewayapp/traceway/backend/app/hooks""github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional"traceway "go.tracewayapp.com")@@ -33,7 +34,7 @@ func evaluateEventRules(event hooks.ReportEvent) {defer traceway.Recover()rules, err := db.ExecuteTransaction(func(tx *sql.Tx) ([]*models.NotificationRuleWithChannel, error) {- return repositories.NotificationRuleRepository.FindEnabledEventRules(tx, event.ProjectId)+ return transactional.NotificationRuleRepository.FindEnabledEventRules(tx, event.ProjectId)})if err != nil {traceway.CaptureException(fmt.Errorf("failed to load event notification rules: %w", err))@@ -126,9 +127,9 @@ func resolveTraceName(ctx context.Context, projectId uuid.UUID, traceId *uuid.UU}switch traceType {case "task":- task, err := repositories.TaskRepository.FindById(ctx, projectId, *traceId, recordedAt)+ task, err := telemetry.TaskRepository.FindById(ctx, projectId, *traceId, recordedAt)if task == nil && err == nil && recordedAt != nil {- task, err = repositories.TaskRepository.FindById(ctx, projectId, *traceId, nil)+ task, err = telemetry.TaskRepository.FindById(ctx, projectId, *traceId, nil)}if err != nil {traceway.CaptureException(fmt.Errorf("failed to resolve task name for notification: %w", err))@@ -139,9 +140,9 @@ func resolveTraceName(ctx context.Context, projectId uuid.UUID, traceId *uuid.UU}return task.TaskNamecase "ai_trace":- trace, err := repositories.AiTraceRepository.FindById(ctx, projectId, *traceId, recordedAt)+ trace, err := telemetry.AiTraceRepository.FindById(ctx, projectId, *traceId, recordedAt)if trace == nil && err == nil && recordedAt != nil {- trace, err = repositories.AiTraceRepository.FindById(ctx, projectId, *traceId, nil)+ trace, err = telemetry.AiTraceRepository.FindById(ctx, projectId, *traceId, nil)}if err != nil {traceway.CaptureException(fmt.Errorf("failed to resolve ai trace name for notification: %w", err))@@ -152,9 +153,9 @@ func resolveTraceName(ctx context.Context, projectId uuid.UUID, traceId *uuid.UU}return trace.TraceNamedefault:- endpoint, err := repositories.EndpointRepository.FindById(ctx, projectId, *traceId, recordedAt)+ endpoint, err := telemetry.EndpointRepository.FindById(ctx, projectId, *traceId, recordedAt)if endpoint == nil && err == nil && recordedAt != nil {- endpoint, err = repositories.EndpointRepository.FindById(ctx, projectId, *traceId, nil)+ endpoint, err = telemetry.EndpointRepository.FindById(ctx, projectId, *traceId, nil)}if err != nil {traceway.CaptureException(fmt.Errorf("failed to resolve endpoint name for notification: %w", err))@@ -169,7 +170,7 @@ func resolveTraceName(ctx context.Context, projectId uuid.UUID, traceId *uuid.UUfunc getProjectName(projectId uuid.UUID) string {project, err := db.ExecuteTransaction(func(tx *sql.Tx) (*models.Project, error) {- return repositories.ProjectRepository.FindById(tx, projectId)+ return transactional.ProjectRepository.FindById(tx, projectId)})if err != nil || project == nil {return ""diff --git a/backend/app/notifications/evaluator_polled.go b/backend/app/notifications/evaluator_polled.goindex 3cd7f699..30e77e15 100644--- a/backend/app/notifications/evaluator_polled.go+++ b/backend/app/notifications/evaluator_polled.go@@ -1,4 +1,4 @@-//go:build pgch+//go:build telemetry_chpackage notificationsdiff --git a/backend/app/notifications/evaluator_polled_sqlite.go b/backend/app/notifications/evaluator_polled_sqlite.goindex 0d096e78..f418c355 100644--- a/backend/app/notifications/evaluator_polled_sqlite.go+++ b/backend/app/notifications/evaluator_polled_sqlite.go@@ -1,4 +1,4 @@-//go:build !pgch+//go:build !telemetry_chpackage notifications@@ -12,7 +12,7 @@ import ("github.com/google/uuid""github.com/tracewayapp/traceway/backend/app/db""github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry")type EvalResult struct {@@ -44,8 +44,8 @@ var polledEvaluators = map[string]RuleEvaluator{type errorRateConfig struct {ThresholdPercent float64 `json:"thresholdPercent"`- LookbackMinutes int `json:"lookbackMinutes"`- MinRequests int `json:"minRequests"`+ LookbackMinutes int `json:"lookbackMinutes"`+ MinRequests int `json:"minRequests"`}func evaluateErrorRateThreshold(ctx context.Context, rule *models.NotificationRule, projectId uuid.UUID) (*EvalResult, error) {@@ -361,12 +361,12 @@ func evaluateNoData(ctx context.Context, rule *models.NotificationRule, projectIif cfg.DataType == "any" {tables := []string{"endpoints", "exception_stack_traces", "metric_points", "tasks"}for _, t := range tables {- var maxTs string+ var maxTs sql.NullStringerr := db.TelemetryDB.QueryRowContext(ctx,- fmt.Sprintf("SELECT COALESCE(MAX(recorded_at), '') FROM %s WHERE project_id = ?", t),+ fmt.Sprintf("SELECT MAX(recorded_at) FROM %s WHERE project_id = ?", t),pid).Scan(&maxTs)- if err == nil && maxTs != "" {- if parsed, pErr := time.Parse(time.RFC3339Nano, maxTs); pErr == nil && parsed.After(threshold) {+ if err == nil && maxTs.Valid && maxTs.String != "" {+ if parsed, pErr := time.Parse(time.RFC3339Nano, maxTs.String); pErr == nil && parsed.After(threshold) {return &EvalResult{Fired: false}, nil}}@@ -390,16 +390,16 @@ func evaluateNoData(ctx context.Context, rule *models.NotificationRule, projectIreturn nil, fmt.Errorf("unknown data type: %s", cfg.DataType)}- var maxTs string+ var maxTs sql.NullStringerr := db.TelemetryDB.QueryRowContext(ctx,- fmt.Sprintf("SELECT COALESCE(MAX(recorded_at), '') FROM %s WHERE project_id = ?", table),+ fmt.Sprintf("SELECT MAX(recorded_at) FROM %s WHERE project_id = ?", table),pid).Scan(&maxTs)if err != nil {return nil, err}- if maxTs != "" {- if parsed, pErr := time.Parse(time.RFC3339Nano, maxTs); pErr == nil && parsed.After(threshold) {+ if maxTs.Valid && maxTs.String != "" {+ if parsed, pErr := time.Parse(time.RFC3339Nano, maxTs.String); pErr == nil && parsed.After(threshold) {return &EvalResult{Fired: false}, nil}}@@ -703,14 +703,20 @@ func computeImpactEndpoints(ctx context.Context, projectId uuid.UUID, minRequestreturn nil, nil}- p99s := make(map[string]float64, len(candidates))- pRows, err := db.TelemetryDB.QueryContext(ctx, `SELECT endpoint, duration FROM (+ p99Query := `SELECT endpoint, duration FROM (SELECT endpoint, duration,ROW_NUMBER() OVER (PARTITION BY endpoint ORDER BY duration) AS rn,COUNT(*) OVER (PARTITION BY endpoint) AS cntFROM endpoints WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ? AND is_stream = 0- ) WHERE rn = CAST(0.99 * (cnt - 1) AS INTEGER) + 1`,- pid, fromStr, nowStr)+ ) WHERE rn = CAST(0.99 * (cnt - 1) AS INTEGER) + 1`+ if db.IsDuckDBTelemetry() {+ p99Query = `SELECT endpoint, CAST(quantile_cont(duration, 0.99) AS BIGINT) as duration+ FROM endpoints WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ? AND is_stream = 0+ GROUP BY endpoint`+ }++ p99s := make(map[string]float64, len(candidates))+ pRows, err := db.TelemetryDB.QueryContext(ctx, p99Query, pid, fromStr, nowStr)if err != nil {return nil, err}@@ -732,7 +738,7 @@ func computeImpactEndpoints(ctx context.Context, projectId uuid.UUID, minRequestfor _, c := range candidates {c.p99 = p99s[c.endpoint]- impact := repositories.ComputeImpactScore(c.endpoint, c.totalCount, c.satisfied, c.tolerating, c.bad, c.clientErrors, c.p99, c.offsetMs)+ impact := telemetry.ComputeImpactScore(c.endpoint, c.totalCount, c.satisfied, c.tolerating, c.bad, c.clientErrors, c.p99, c.offsetMs)if impact >= minImpactThreshold {c.impact = impactresult = append(result, c)diff --git a/backend/app/notifications/impact_shared.go b/backend/app/notifications/impact_shared.goindex 28460bf9..094fabd7 100644--- a/backend/app/notifications/impact_shared.go+++ b/backend/app/notifications/impact_shared.go@@ -9,7 +9,7 @@ import ("github.com/google/uuid""github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry")const minImpactThreshold = 0.25@@ -121,7 +121,7 @@ func evaluateImpactScore(ctx context.Context, rule *models.NotificationRule, proif prevSet[ep] {continue}- reason := repositories.ComputeImpactReason(+ reason := telemetry.ComputeImpactReason(ep, data.totalCount, data.satisfied, data.tolerating,data.bad, data.clientErrors, data.p99, data.offsetMs,)diff --git a/backend/app/notifications/notifications_sqlite_test.go b/backend/app/notifications/notifications_sqlite_test.goindex 466c56aa..40a16287 100644--- a/backend/app/notifications/notifications_sqlite_test.go+++ b/backend/app/notifications/notifications_sqlite_test.go@@ -1,4 +1,4 @@-//go:build !pgch+//go:build !telemetry_chpackage notificationsdiff --git a/backend/app/recordings/uploader.go b/backend/app/recordings/uploader.goindex fc9de56c..96af2f44 100644--- a/backend/app/recordings/uploader.go+++ b/backend/app/recordings/uploader.go@@ -12,7 +12,7 @@ import ("github.com/tracewayapp/traceway/backend/app/config""github.com/tracewayapp/traceway/backend/app/models""github.com/tracewayapp/traceway/backend/app/monitoring"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry""github.com/tracewayapp/traceway/backend/app/storage"traceway "go.tracewayapp.com")@@ -193,7 +193,7 @@ func (p *pool) batcher(ctx context.Context) {if len(batch) == 0 {return}- if err := repositories.SessionRecordingRepository.InsertAsync(ctx, batch); err != nil {+ if err := telemetry.SessionRecordingRepository.InsertAsync(ctx, batch); err != nil {p.failed.Add(uint64(len(batch)))traceway.CaptureException(traceway.NewStackTraceErrorf("failed to insert batch of %d session recording rows: %w", len(batch), err))}@@ -262,4 +262,3 @@ func (p *pool) metricsLoop(ctx context.Context) {}}}-diff --git a/backend/app/repositories/auth_tokens_common.go b/backend/app/repositories/auth_tokens_common.godeleted file mode 100644index d91cc8cc..00000000--- a/backend/app/repositories/auth_tokens_common.go+++ /dev/null@@ -1,41 +0,0 @@-package repositories--import (- "crypto/sha256"- "database/sql"- "encoding/hex"- "fmt"- "time"-)--const authTimeLayout = "2006-01-02T15:04:05.000000000Z07:00"--func hashAuthToken(plaintext string) string {- sum := sha256.Sum256([]byte(plaintext))- return hex.EncodeToString(sum[:])-}--func formatAuthTime(t time.Time) string {- return t.UTC().Format(authTimeLayout)-}--func parseAuthTime(s string) (time.Time, error) {- layouts := []string{authTimeLayout, time.RFC3339Nano, time.RFC3339, "2006-01-02 15:04:05.999999999-07:00", "2006-01-02 15:04:05"}- for _, layout := range layouts {- if parsed, err := time.Parse(layout, s); err == nil {- return parsed.UTC(), nil- }- }- return time.Time{}, fmt.Errorf("auth: cannot parse time %q", s)-}--func parseNullableAuthTime(ns sql.NullString) (*time.Time, error) {- if !ns.Valid || ns.String == "" {- return nil, nil- }- t, err := parseAuthTime(ns.String)- if err != nil {- return nil, err- }- return &t, nil-}diff --git a/backend/app/repositories/session_filter.go b/backend/app/repositories/session_filter.godeleted file mode 100644index c640048c..00000000--- a/backend/app/repositories/session_filter.go+++ /dev/null@@ -1,9 +0,0 @@-package repositories--// SessionAttributeFilter narrows the sessions list by an exact key=value-// match against the JSON `attributes` blob. Defined in a tag-neutral file-// so both the ClickHouse and SQLite repository builds see the same type.-type SessionAttributeFilter struct {- Key string- Value string-}diff --git a/backend/app/repositories/telemetry/ai_trace_repository_test.go b/backend/app/repositories/telemetry/ai_trace_repository_test.gonew file mode 100644index 00000000..7ef1492d--- /dev/null+++ b/backend/app/repositories/telemetry/ai_trace_repository_test.go@@ -0,0 +1,62 @@+package telemetry++import (+ "context"+ "testing"+ "time"++ "github.com/google/uuid"+ "github.com/tracewayapp/traceway/backend/app/models"+)++func TestAiTraceRepository_GetTraceNameStats(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ now := truncateMs(time.Now().UTC())++ traces := []models.AiTrace{+ makeAiTrace(projectId, "summarize", 100*time.Millisecond, 100, 0.5, now),+ makeAiTrace(projectId, "summarize", 200*time.Millisecond, 200, 1.0, now.Add(time.Minute)),+ makeAiTrace(projectId, "summarize", 300*time.Millisecond, 300, 1.5, now.Add(2*time.Minute)),+ }++ if err := AiTraceRepository.InsertAsync(ctx, traces); err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ start := now.Add(-time.Hour)+ end := now.Add(time.Hour)+ stats, err := AiTraceRepository.GetTraceNameStats(ctx, projectId, "summarize", start, end)+ if err != nil {+ t.Fatalf("GetTraceNameStats failed: %v", err)+ }++ if stats.Count != 3 {+ t.Errorf("expected count 3, got %d", stats.Count)+ }+ if stats.TotalTokens != 600 {+ t.Errorf("expected total tokens 600, got %d", stats.TotalTokens)+ }+ assertApproxEqual(t, "TotalCost", stats.TotalCost, 3.0, 0.001)+ assertApproxEqual(t, "AvgDuration", stats.AvgDuration, 200.0, 1.0)+ assertApproxEqual(t, "MedianDuration", stats.MedianDuration, 200.0, 1.0)+ assertApproxEqual(t, "AvgInputTokens", stats.AvgInputTokens, 100.0, 0.001)+}++func TestAiTraceRepository_GetTraceNameStats_EmptyWindow(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ now := time.Now().UTC()++ stats, err := AiTraceRepository.GetTraceNameStats(ctx, uuid.New(), "missing", now.Add(-time.Hour), now)+ if err != nil {+ t.Fatalf("GetTraceNameStats failed: %v", err)+ }+ if stats.Count != 0 {+ t.Errorf("expected count 0, got %d", stats.Count)+ }+ if stats.TotalTokens != 0 {+ t.Errorf("expected total tokens 0, got %d", stats.TotalTokens)+ }+}diff --git a/backend/app/repositories/attribute_filter_dotted_key_test.go b/backend/app/repositories/telemetry/attribute_filter_dotted_key_test.gosimilarity index 98%rename from backend/app/repositories/attribute_filter_dotted_key_test.gorename to backend/app/repositories/telemetry/attribute_filter_dotted_key_test.goindex 7d53e4b7..3a2b5553 100644--- a/backend/app/repositories/attribute_filter_dotted_key_test.go+++ b/backend/app/repositories/telemetry/attribute_filter_dotted_key_test.go@@ -1,6 +1,6 @@-//go:build !pgch+//go:build !telemetry_ch-package repositories+package telemetryimport ("context"diff --git a/backend/app/repositories/ai_trace.repository.go b/backend/app/repositories/telemetry/clickhouse/ai_trace.repository.gosimilarity index 97%rename from backend/app/repositories/ai_trace.repository.gorename to backend/app/repositories/telemetry/clickhouse/ai_trace.repository.goindex ae84df36..485d8402 100644--- a/backend/app/repositories/ai_trace.repository.go+++ b/backend/app/repositories/telemetry/clickhouse/ai_trace.repository.go@@ -1,12 +1,13 @@-//go:build pgch+//go:build telemetry_ch-package repositories+package clickhouseimport ("context""database/sql""encoding/json""errors"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/shared""strings""time"@@ -256,7 +257,7 @@ func (r *aiTraceRepository) FindById(ctx context.Context, projectId, traceId uuiWHERE project_id = ? AND id = ?`args := []any{projectId, traceId}if recordedAt != nil {- from, to := traceWindowBounds(*recordedAt)+ from, to := shared.TraceWindowBounds(*recordedAt)query += ` AND recorded_at >= ? AND recorded_at <= ?`args = append(args, from, to)}@@ -311,7 +312,7 @@ func (r *aiTraceRepository) FindByDistributedTraceId(ctx context.Context, distriFROM ai_tracesWHERE distributed_trace_id = ? AND project_id IN (` + strings.Join(placeholders, ",") + `)`if recordedAt != nil {- from, to := distributedTraceWindowBounds(*recordedAt)+ from, to := shared.DistributedTraceWindowBounds(*recordedAt)query += ` AND recorded_at >= ? AND recorded_at <= ?`args = append(args, from, to)}@@ -349,4 +350,4 @@ func (r *aiTraceRepository) FindByDistributedTraceId(ctx context.Context, distrireturn traces, nil}-var AiTraceRepository = aiTraceRepository{}+var AiTraceRepository = &aiTraceRepository{}diff --git a/backend/app/repositories/endpoint.repository.go b/backend/app/repositories/telemetry/clickhouse/endpoint.repository.gosimilarity index 97%rename from backend/app/repositories/endpoint.repository.gorename to backend/app/repositories/telemetry/clickhouse/endpoint.repository.goindex 462cb1cc..8415e112 100644--- a/backend/app/repositories/endpoint.repository.go+++ b/backend/app/repositories/telemetry/clickhouse/endpoint.repository.go@@ -1,14 +1,15 @@-//go:build pgch+//go:build telemetry_ch-package repositories+package clickhouseimport (- "github.com/tracewayapp/traceway/backend/app/chdb"- "github.com/tracewayapp/traceway/backend/app/models""context""database/sql""encoding/json""errors"+ "github.com/tracewayapp/traceway/backend/app/chdb"+ "github.com/tracewayapp/traceway/backend/app/models"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/shared""time""github.com/ClickHouse/clickhouse-go/v2/lib/driver"@@ -271,7 +272,7 @@ func (e *endpointRepository) FindGroupedByEndpoint(ctx context.Context, projectI// Latency/Apdex are zero for streams. Impact came from the// stream-specific branch of the SQL (status-code components only);// the reason is computed from the same status-code aggregates.- s.ImpactReason = ComputeStreamImpactReason(s.Endpoint, s.Count, serverErrorCount, clientErrorCount)+ s.ImpactReason = shared.ComputeStreamImpactReason(s.Endpoint, s.Count, serverErrorCount, clientErrorCount)stats = append(stats, s)continue}@@ -279,7 +280,7 @@ func (e *endpointRepository) FindGroupedByEndpoint(ctx context.Context, projectIs.P95Duration = time.Duration(p95)s.P99Duration = time.Duration(p99)s.AvgDuration = time.Duration(avg)- s.ImpactReason = ComputeImpactReason(s.Endpoint, s.Count, satisfiedCount, toleratingCount, badCount, clientErrorCount, p99, offsetMs)+ s.ImpactReason = shared.ComputeImpactReason(s.Endpoint, s.Count, satisfiedCount, toleratingCount, badCount, clientErrorCount, p99, offsetMs)stats = append(stats, s)}@@ -344,7 +345,7 @@ func (e *endpointRepository) FindById(ctx context.Context, projectId, endpointIdWHERE project_id = ? AND id = ?`args := []any{projectId, endpointId}if recordedAt != nil {- from, to := traceWindowBounds(*recordedAt)+ from, to := shared.TraceWindowBounds(*recordedAt)query += ` AND recorded_at >= ? AND recorded_at <= ?`args = append(args, from, to)}@@ -627,7 +628,7 @@ func (e *endpointRepository) FindWorstEndpoints(ctx context.Context, projectId us.P95Duration = time.Duration(p95)s.P99Duration = time.Duration(p99)s.AvgDuration = time.Duration(avg)- s.ImpactReason = ComputeImpactReason(s.Endpoint, s.Count, satisfiedCount, toleratingCount, badCount, clientErrorCount, p99, offsetMs)+ s.ImpactReason = shared.ComputeImpactReason(s.Endpoint, s.Count, satisfiedCount, toleratingCount, badCount, clientErrorCount, p99, offsetMs)stats = append(stats, s)}@@ -653,7 +654,7 @@ func (e *endpointRepository) GetEndpointStats(ctx context.Context, projectId uuicountIf(duration <= 500000000 AND status_code < 500 AND is_stream = 0) +(countIf(duration > 500000000 AND duration <= 2000000000 AND status_code < 500 AND is_stream = 0) * 0.5),0) as satisfied_tolerating,- max(is_stream) as is_stream,+ max(is_stream) as has_stream,countIf(is_stream = 0) as non_stream_countFROM endpointsWHERE project_id = ? AND endpoint = ? AND recorded_at >= ? AND recorded_at <= ?`@@ -854,7 +855,7 @@ func (e *endpointRepository) FindByDistributedTraceId(ctx context.Context, distrWHERE distributed_trace_id = ? AND project_id IN (?)`args := []any{distributedTraceId, projectIds}if recordedAt != nil {- from, to := distributedTraceWindowBounds(*recordedAt)+ from, to := shared.DistributedTraceWindowBounds(*recordedAt)query += ` AND recorded_at >= ? AND recorded_at <= ?`args = append(args, from, to)}@@ -884,4 +885,4 @@ func (e *endpointRepository) FindByDistributedTraceId(ctx context.Context, distrreturn endpoints, nil}-var EndpointRepository = endpointRepository{}+var EndpointRepository = &endpointRepository{}diff --git a/backend/app/repositories/exception_stack_trace.repository.go b/backend/app/repositories/telemetry/clickhouse/exception_stack_trace.repository.gosimilarity index 98%rename from backend/app/repositories/exception_stack_trace.repository.gorename to backend/app/repositories/telemetry/clickhouse/exception_stack_trace.repository.goindex e7507aa3..b2646b03 100644--- a/backend/app/repositories/exception_stack_trace.repository.go+++ b/backend/app/repositories/telemetry/clickhouse/exception_stack_trace.repository.go@@ -1,14 +1,15 @@-//go:build pgch+//go:build telemetry_ch-package repositories+package clickhouseimport (- "github.com/tracewayapp/traceway/backend/app/chdb"- "github.com/tracewayapp/traceway/backend/app/models""context""database/sql""encoding/json""errors"+ "github.com/tracewayapp/traceway/backend/app/chdb"+ "github.com/tracewayapp/traceway/backend/app/models"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/shared""strings""time"@@ -408,7 +409,7 @@ func (e *exceptionStackTraceRepository) FindAllByTraceId(ctx context.Context, prWHERE project_id = ? AND trace_id = ?`args := []any{projectId, traceId}if recordedAt != nil {- from, to := traceWindowBounds(*recordedAt)+ from, to := shared.TraceWindowBounds(*recordedAt)query += ` AND recorded_at >= ? AND recorded_at <= ?`args = append(args, from, to)}@@ -455,7 +456,7 @@ func (e *exceptionStackTraceRepository) FindById(ctx context.Context, projectIdWHERE project_id = ? AND id = ?`args := []any{projectId, id}if recordedAt != nil {- from, to := traceWindowBounds(*recordedAt)+ from, to := shared.TraceWindowBounds(*recordedAt)query += ` AND recorded_at >= ? AND recorded_at <= ?`args = append(args, from, to)}@@ -488,7 +489,7 @@ func (e *exceptionStackTraceRepository) FindByDistributedTraceId(ctx context.ConWHERE distributed_trace_id = ? AND project_id IN (?) AND is_message = false`args := []any{distributedTraceId, projectIds}if recordedAt != nil {- from, to := distributedTraceWindowBounds(*recordedAt)+ from, to := shared.DistributedTraceWindowBounds(*recordedAt)query += ` AND recorded_at >= ? AND recorded_at <= ?`args = append(args, from, to)}@@ -520,4 +521,4 @@ func (e *exceptionStackTraceRepository) FindByDistributedTraceId(ctx context.Conreturn exceptions, nil}-var ExceptionStackTraceRepository = exceptionStackTraceRepository{}+var ExceptionStackTraceRepository = &exceptionStackTraceRepository{}diff --git a/backend/app/repositories/fired_notification.repository.go b/backend/app/repositories/telemetry/clickhouse/fired_notification.repository.gosimilarity index 87%rename from backend/app/repositories/fired_notification.repository.gorename to backend/app/repositories/telemetry/clickhouse/fired_notification.repository.goindex 868fdf43..c0154c10 100644--- a/backend/app/repositories/fired_notification.repository.go+++ b/backend/app/repositories/telemetry/clickhouse/fired_notification.repository.go@@ -1,9 +1,10 @@-//go:build pgch+//go:build telemetry_ch-package repositories+package clickhouseimport ("context"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/shared""time""github.com/google/uuid"@@ -11,26 +12,9 @@ import ("github.com/tracewayapp/traceway/backend/app/models")-type FiredNotification struct {- ProjectId uuid.UUID- RuleId int- RuleType string- RuleName string- ChannelType string- ChannelName string- Severity string- Subject string- Body string- Status string- ErrorMsg string- Endpoint string- URL string- FiredAt time.Time-}-type firedNotificationRepository struct{}-func (r *firedNotificationRepository) Insert(ctx context.Context, n FiredNotification) error {+func (r *firedNotificationRepository) Insert(ctx context.Context, n shared.FiredNotification) error {batch, err := chdb.Conn.PrepareBatch(chdb.BatchCtx(),"INSERT INTO fired_notifications (project_id, rule_id, rule_type, rule_name, channel_type, channel_name, severity, subject, body, status, error_message, endpoint, url, fired_at)",@@ -125,4 +109,4 @@ func (r *firedNotificationRepository) FindLastFiredPerRule(ctx context.Context)return result, nil}-var FiredNotificationRepository = firedNotificationRepository{}+var FiredNotificationRepository = &firedNotificationRepository{}diff --git a/backend/app/repositories/log_record.repository.go b/backend/app/repositories/telemetry/clickhouse/log_record.repository.gosimilarity index 87%rename from backend/app/repositories/log_record.repository.gorename to backend/app/repositories/telemetry/clickhouse/log_record.repository.goindex a9a386e1..110269ef 100644--- a/backend/app/repositories/log_record.repository.go+++ b/backend/app/repositories/telemetry/clickhouse/log_record.repository.go@@ -1,11 +1,11 @@-//go:build pgch+//go:build telemetry_ch-package repositories+package clickhouseimport ("context"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/shared""strings"- "time""github.com/google/uuid"@@ -13,32 +13,6 @@ import ("github.com/tracewayapp/traceway/backend/app/models")-// LogAttributeFilter selects logs by an exact attribute value. Scope is one of-// "resource", "scope", or "log"; picks which of the three Map columns to query.-// Leverages the map bloom-filter indexes — cheap even on wide time ranges.-type LogAttributeFilter struct {- Scope string- Key string- Value string-}--type LogSearchParams struct {- ProjectId uuid.UUID- FromDate time.Time- ToDate time.Time- Search string- SearchType string- MinSeverity uint8- ServiceName string- TraceId string- TraceIds []string- AttributeFilters []LogAttributeFilter- OrderBy string- SortDirection string- Page int- PageSize int-}-type logRecordRepository struct{}func (r *logRecordRepository) InsertAsync(ctx context.Context, records []models.LogRecord) error {@@ -94,7 +68,7 @@ func (r *logRecordRepository) InsertAsync(ctx context.Context, records []models.return batch.Send()}-func (r *logRecordRepository) Search(ctx context.Context, params LogSearchParams) ([]models.LogRecord, int64, error) {+func (r *logRecordRepository) Search(ctx context.Context, params shared.LogSearchParams) ([]models.LogRecord, int64, error) {where, args := r.buildWhere(params)countQuery := "SELECT count() FROM log_records WHERE " + where@@ -211,7 +185,7 @@ func (r *logRecordRepository) FindByTraceId(ctx context.Context, projectId uuid.return records, nil}-func (r *logRecordRepository) buildWhere(params LogSearchParams) (string, []interface{}) {+func (r *logRecordRepository) buildWhere(params shared.LogSearchParams) (string, []interface{}) {clauses := []string{"project_id = ?", "timestamp >= ?", "timestamp <= ?"}args := []interface{}{params.ProjectId, params.FromDate, params.ToDate}@@ -308,4 +282,4 @@ func (r *logRecordRepository) resolveOrderBy(orderBy string) string {return "timestamp"}-var LogRecordRepository = logRecordRepository{}+var LogRecordRepository = &logRecordRepository{}diff --git a/backend/app/repositories/metric_point.repository.go b/backend/app/repositories/telemetry/clickhouse/metric_point.repository.gosimilarity index 98%rename from backend/app/repositories/metric_point.repository.gorename to backend/app/repositories/telemetry/clickhouse/metric_point.repository.goindex 14f55bc4..3adaa033 100644--- a/backend/app/repositories/metric_point.repository.go+++ b/backend/app/repositories/telemetry/clickhouse/metric_point.repository.go@@ -1,11 +1,11 @@-//go:build pgch+//go:build telemetry_ch-package repositories+package clickhouseimport (+ "context""github.com/tracewayapp/traceway/backend/app/chdb""github.com/tracewayapp/traceway/backend/app/models"- "context""time""github.com/ClickHouse/clickhouse-go/v2/lib/driver"@@ -261,4 +261,4 @@ func (r *metricPointRepository) GetAverageByIntervalPerServer(ctx context.Contexreturn result, nil}-var MetricPointRepository = metricPointRepository{}+var MetricPointRepository = &metricPointRepository{}diff --git a/backend/app/repositories/profile.repository.go b/backend/app/repositories/telemetry/clickhouse/profile.repository.gosimilarity index 95%rename from backend/app/repositories/profile.repository.gorename to backend/app/repositories/telemetry/clickhouse/profile.repository.goindex cac351a9..1cb1e277 100644--- a/backend/app/repositories/profile.repository.go+++ b/backend/app/repositories/telemetry/clickhouse/profile.repository.go@@ -1,11 +1,12 @@-//go:build pgch+//go:build telemetry_ch-package repositories+package clickhouseimport ("context""encoding/json""fmt"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/shared""sort""time"@@ -291,7 +292,7 @@ func (r *profileRepository) GetSeries(ctx context.Context, projectId uuid.UUID,}points = append(points, p)}- normalizeSeriesPoints(points, normalize, isGauge, intervalMinutes)+ shared.NormalizeSeriesPoints(points, normalize, isGauge, intervalMinutes)return points, nil}@@ -382,7 +383,7 @@ func (r *profileRepository) GetSeriesBreakdown(ctx context.Context, projectId uuif intervalMinutes < 1 {intervalMinutes = 1}- limit = clampBreakdownLimit(limit)+ limit = shared.ClampBreakdownLimit(limit)agg := "sum"if isGauge {agg = "avg"@@ -461,7 +462,7 @@ func (r *profileRepository) GetSeriesBreakdown(ctx context.Context, projectId uuif err := srows.Err(); err != nil {return nil, err}- normalizeSeriesPoints(points, normalize, isGauge, intervalMinutes)+ shared.NormalizeSeriesPoints(points, normalize, isGauge, intervalMinutes)groups = append(groups, models.ProfileSeriesGroup{Key: key, Points: points})}return groups, nil@@ -523,7 +524,7 @@ func chDimExpr(dimension string) (string, []interface{}, bool) {case "server_name":return "server_name", nil, true}- key, ok := breakdownLabelKey(dimension)+ key, ok := shared.BreakdownLabelKey(dimension)if !ok || key == "" {return "", nil, false}@@ -549,4 +550,10 @@ func chLabelFilter(qualifier string, filters map[string]string) (string, []interreturn clause, args}-var ProfileRepository = profileRepository{}+var ProfileRepository = &profileRepository{}++func (r *profileRepository) DiscoverLabels(ctx context.Context, projectId uuid.UUID, service, profileType string, from, to time.Time, allowKeys []string) (map[string][]string, error) {+ return shared.DiscoverLabels(ctx, allowKeys, func(ctx context.Context, key string) ([]string, error) {+ return r.distinctLabelValues(ctx, projectId, service, profileType, key, from, to)+ })+}diff --git a/backend/app/repositories/session.repository.go b/backend/app/repositories/telemetry/clickhouse/session.repository.gosimilarity index 92%rename from backend/app/repositories/session.repository.gorename to backend/app/repositories/telemetry/clickhouse/session.repository.goindex cac713ad..17865709 100644--- a/backend/app/repositories/session.repository.go+++ b/backend/app/repositories/telemetry/clickhouse/session.repository.go@@ -1,11 +1,12 @@-//go:build pgch+//go:build telemetry_ch-package repositories+package clickhouseimport ("context""database/sql""errors"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/shared""strings""time"@@ -43,7 +44,7 @@ func (r *sessionRepository) CountBetween(ctx context.Context, projectId uuid.UUIreturn int64(count), err}-func (r *sessionRepository) FindAll(ctx context.Context, projectId uuid.UUID, fromDate, toDate time.Time, page, pageSize int, orderBy string, sortDirection string, search string, attributeFilters []SessionAttributeFilter) ([]models.Session, int64, error) {+func (r *sessionRepository) FindAll(ctx context.Context, projectId uuid.UUID, fromDate, toDate time.Time, page, pageSize int, orderBy string, sortDirection string, search string, attributeFilters []shared.SessionAttributeFilter) ([]models.Session, int64, error) {whereExtra, extraArgs := buildSessionFilterClause(search, attributeFilters)countArgs := []interface{}{projectId, fromDate, toDate}@@ -97,7 +98,7 @@ func (r *sessionRepository) FindById(ctx context.Context, projectId, sessionId uWHERE project_id = ? AND id = ?`args := []any{projectId, sessionId}if startedAt != nil {- from, to := traceWindowBounds(*startedAt)+ from, to := shared.TraceWindowBounds(*startedAt)query += ` AND started_at >= ? AND started_at <= ?`args = append(args, from, to)}@@ -123,7 +124,7 @@ func (r *sessionRepository) FindById(ctx context.Context, projectId, sessionId u// Each attribute filter adds an exact-match clause via the `attributes[?]`// Map subscript, which is O(1) per row and indexed by the bloom filters on// `mapKeys(attributes)` / `mapValues(attributes)`.-func buildSessionFilterClause(search string, filters []SessionAttributeFilter) (string, []interface{}) {+func buildSessionFilterClause(search string, filters []shared.SessionAttributeFilter) (string, []interface{}) {var sb strings.Builderargs := []interface{}{}if s := strings.TrimSpace(search); s != "" {@@ -144,4 +145,4 @@ func buildSessionFilterClause(search string, filters []SessionAttributeFilter) (return sb.String(), args}-var SessionRepository = sessionRepository{}+var SessionRepository = &sessionRepository{}diff --git a/backend/app/repositories/session_recording.repository.go b/backend/app/repositories/telemetry/clickhouse/session_recording.repository.gosimilarity index 95%rename from backend/app/repositories/session_recording.repository.gorename to backend/app/repositories/telemetry/clickhouse/session_recording.repository.goindex 19223e9c..f8283f0d 100644--- a/backend/app/repositories/session_recording.repository.go+++ b/backend/app/repositories/telemetry/clickhouse/session_recording.repository.go@@ -1,13 +1,13 @@-//go:build pgch+//go:build telemetry_ch-package repositories+package clickhouseimport (- "github.com/tracewayapp/traceway/backend/app/chdb"- "github.com/tracewayapp/traceway/backend/app/models""context""database/sql""errors"+ "github.com/tracewayapp/traceway/backend/app/chdb"+ "github.com/tracewayapp/traceway/backend/app/models""github.com/google/uuid")@@ -65,4 +65,4 @@ func (r *sessionRecordingRepository) FindBySessionId(ctx context.Context, projecreturn recordings, nil}-var SessionRecordingRepository = sessionRecordingRepository{}+var SessionRecordingRepository = &sessionRecordingRepository{}diff --git a/backend/app/repositories/span.repository.go b/backend/app/repositories/telemetry/clickhouse/span.repository.gosimilarity index 90%rename from backend/app/repositories/span.repository.gorename to backend/app/repositories/telemetry/clickhouse/span.repository.goindex cee72ef5..e7d3285c 100644--- a/backend/app/repositories/span.repository.go+++ b/backend/app/repositories/telemetry/clickhouse/span.repository.go@@ -1,10 +1,11 @@-//go:build pgch+//go:build telemetry_ch-package repositories+package clickhouseimport ("context""encoding/json"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/shared""time""github.com/tracewayapp/traceway/backend/app/chdb"@@ -54,7 +55,7 @@ func (r *spanRepository) FindByTraceId(ctx context.Context, projectId, traceId uWHERE project_id = ? AND trace_id = ?`args := []any{projectId, traceId}if recordedAt != nil {- from, to := traceWindowBounds(*recordedAt)+ from, to := shared.TraceWindowBounds(*recordedAt)query += ` AND recorded_at >= ? AND recorded_at <= ?`args = append(args, from, to)}@@ -88,4 +89,4 @@ func (r *spanRepository) FindByTraceId(ctx context.Context, projectId, traceId ureturn spans, nil}-var SpanRepository = spanRepository{}+var SpanRepository = &spanRepository{}diff --git a/backend/app/repositories/task.repository.go b/backend/app/repositories/telemetry/clickhouse/task.repository.gosimilarity index 98%rename from backend/app/repositories/task.repository.gorename to backend/app/repositories/telemetry/clickhouse/task.repository.goindex de198355..33efcc35 100644--- a/backend/app/repositories/task.repository.go+++ b/backend/app/repositories/telemetry/clickhouse/task.repository.go@@ -1,14 +1,15 @@-//go:build pgch+//go:build telemetry_ch-package repositories+package clickhouseimport (- "github.com/tracewayapp/traceway/backend/app/chdb"- "github.com/tracewayapp/traceway/backend/app/models""context""database/sql""encoding/json""errors"+ "github.com/tracewayapp/traceway/backend/app/chdb"+ "github.com/tracewayapp/traceway/backend/app/models"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/shared""time""github.com/ClickHouse/clickhouse-go/v2/lib/driver"@@ -230,7 +231,7 @@ func (e *taskRepository) FindById(ctx context.Context, projectId, taskId uuid.UUWHERE project_id = ? AND id = ?`args := []any{projectId, taskId}if recordedAt != nil {- from, to := traceWindowBounds(*recordedAt)+ from, to := shared.TraceWindowBounds(*recordedAt)query += ` AND recorded_at >= ? AND recorded_at <= ?`args = append(args, from, to)}@@ -454,7 +455,7 @@ func (e *taskRepository) FindByDistributedTraceId(ctx context.Context, distributWHERE distributed_trace_id = ? AND project_id IN (?)`args := []any{distributedTraceId, projectIds}if recordedAt != nil {- from, to := distributedTraceWindowBounds(*recordedAt)+ from, to := shared.DistributedTraceWindowBounds(*recordedAt)query += ` AND recorded_at >= ? AND recorded_at <= ?`args = append(args, from, to)}@@ -484,4 +485,4 @@ func (e *taskRepository) FindByDistributedTraceId(ctx context.Context, distributreturn tasks, nil}-var TaskRepository = taskRepository{}+var TaskRepository = &taskRepository{}diff --git a/backend/app/repositories/telemetry/duckdb/ai_trace.repository.go b/backend/app/repositories/telemetry/duckdb/ai_trace.repository.gonew file mode 100644index 00000000..f2c8fe1a--- /dev/null+++ b/backend/app/repositories/telemetry/duckdb/ai_trace.repository.go@@ -0,0 +1,448 @@+//go:build telemetry_duckdb++package duckdb++import (+ "context"+ "fmt"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/shared"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/sqlitetypes"+ "sort"+ "strings"+ "time"++ "github.com/duckdb/duckdb-go/v2"+ "github.com/google/uuid"+ "github.com/tracewayapp/lit/v2"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"+)++type aiTraceRowNaming struct{ lit.DefaultDbNamingStrategy }++func (aiTraceRowNaming) GetTableNameFromStructName(string) string {+ return "ai_traces"+}++type aiTraceRow struct {+ Id uuid.UUID `lit:"id"`+ ProjectId uuid.UUID `lit:"project_id"`+ RecordedAt sqlitetypes.SQLiteTime `lit:"recorded_at"`+ Duration int64 `lit:"duration"`+ StatusCode uint8 `lit:"status_code"`+ Model string `lit:"model"`+ ResponseModel string `lit:"response_model"`+ Provider string `lit:"provider"`+ Operation string `lit:"operation"`+ InputTokens int64 `lit:"input_tokens"`+ OutputTokens int64 `lit:"output_tokens"`+ TotalTokens int64 `lit:"total_tokens"`+ CachedTokens int64 `lit:"cached_tokens"`+ ReasoningTokens int64 `lit:"reasoning_tokens"`+ InputCost float64 `lit:"input_cost"`+ OutputCost float64 `lit:"output_cost"`+ TotalCost float64 `lit:"total_cost"`+ TraceName string `lit:"trace_name"`+ UserId string `lit:"user_id"`+ FinishReason string `lit:"finish_reason"`+ ServerName string `lit:"server_name"`+ AppVersion string `lit:"app_version"`+ StorageKey string `lit:"storage_key"`+ Attributes sqlitetypes.SQLiteJSONMap `lit:"attributes"`+ DistributedTraceId *uuid.UUID `lit:"distributed_trace_id"`+ IsRoot bool `lit:"is_root"`+}++type groupedAiTraceRow struct {+ TraceName string `lit:"trace_name"`+ TotalCount uint64 `lit:"total_count"`+ AvgDuration float64 `lit:"avg_duration"`+ P50Duration float64 `lit:"p50_duration"`+ P95Duration float64 `lit:"p95_duration"`+ TotalTokens int64 `lit:"total_tokens"`+ TotalCost float64 `lit:"total_cost"`+ AvgInputTokens float64 `lit:"avg_input_tokens"`+ AvgOutputTokens float64 `lit:"avg_output_tokens"`+ LastSeen time.Time `lit:"last_seen"`+ HasRoot bool `lit:"has_root"`+ HasNonRoot bool `lit:"has_non_root"`+}++type aiTraceDetailStatsRow struct {+ Count int64 `lit:"count"`+ AvgDurationMs float64 `lit:"avg_duration_ms"`+ MedianDurationMs float64 `lit:"median_duration_ms"`+ P95DurationMs float64 `lit:"p95_duration_ms"`+ TotalTokens int64 `lit:"total_tokens"`+ TotalCost float64 `lit:"total_cost"`+ AvgInputTokens float64 `lit:"avg_input_tokens"`+ AvgOutputTokens float64 `lit:"avg_output_tokens"`+}++func init() {+ models.ExtensionModelRegistrations = append(models.ExtensionModelRegistrations, func(driver lit.Driver) {+ lit.RegisterModelWithNaming[aiTraceRow](driver, aiTraceRowNaming{})+ lit.RegisterModel[groupedAiTraceRow](driver)+ lit.RegisterModel[aiTraceDetailStatsRow](driver)+ })+}++func (r *aiTraceRow) toModel() models.AiTrace {+ t := models.AiTrace{+ Id: r.Id,+ ProjectId: r.ProjectId,+ RecordedAt: r.RecordedAt.Time,+ Duration: time.Duration(r.Duration),+ StatusCode: r.StatusCode,+ Model: r.Model,+ ResponseModel: r.ResponseModel,+ Provider: r.Provider,+ Operation: r.Operation,+ InputTokens: r.InputTokens,+ OutputTokens: r.OutputTokens,+ TotalTokens: r.TotalTokens,+ CachedTokens: r.CachedTokens,+ ReasoningTokens: r.ReasoningTokens,+ InputCost: r.InputCost,+ OutputCost: r.OutputCost,+ TotalCost: r.TotalCost,+ TraceName: r.TraceName,+ UserId: r.UserId,+ FinishReason: r.FinishReason,+ ServerName: r.ServerName,+ AppVersion: r.AppVersion,+ StorageKey: r.StorageKey,+ DistributedTraceId: r.DistributedTraceId,+ IsRoot: r.IsRoot,+ }+ if r.Attributes != nil {+ t.Attributes = map[string]string(r.Attributes)+ }+ return t+}++type aiTraceRepository struct{}++func (r *aiTraceRepository) InsertAsync(ctx context.Context, lines []models.AiTrace) error {+ if len(lines) == 0 {+ return nil+ }++ return withAppender(ctx, "ai_traces", func(appender *duckdb.Appender) {++ for _, t := range lines {+ attributesJSON, err := attrJSON(t.Attributes)+ if err != nil {+ captureDroppedRow("ai_traces", err)+ continue+ }++ var distributedTraceId *string+ if t.DistributedTraceId != nil {+ s := t.DistributedTraceId.String()+ distributedTraceId = &s+ }++ isRoot := boolToInt(t.IsRoot)++ // Column order follows the ai_traces DDL exactly: is_root precedes distributed_trace_id.+ if err := appender.AppendRow(+ t.Id.String(),+ t.ProjectId.String(),+ t.RecordedAt.UTC(),+ int64(t.Duration),+ int64(t.StatusCode),+ t.Model,+ t.ResponseModel,+ t.Provider,+ t.Operation,+ t.InputTokens,+ t.OutputTokens,+ t.TotalTokens,+ t.CachedTokens,+ t.ReasoningTokens,+ t.InputCost,+ t.OutputCost,+ t.TotalCost,+ t.TraceName,+ t.UserId,+ t.FinishReason,+ t.ServerName,+ t.AppVersion,+ t.StorageKey,+ attributesJSON,+ isRoot,+ nullableString(distributedTraceId),+ ); err != nil {+ captureDroppedRow("ai_traces", err)+ }+ }++ })+}++func (r *aiTraceRepository) FindGroupedByTraceName(ctx context.Context, projectId uuid.UUID, fromDate, toDate time.Time, page, pageSize int, orderBy, sortDirection, search, rootFilter string) ([]models.AiTraceStats, int64, error) {+ params := lit.P{"project_id": projectId, "from": fromDate.UTC(), "to": toDate.UTC()}++ whereClause := "project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to"+ if search != "" {+ whereClause += " AND INSTR(LOWER(trace_name), LOWER(:search)) > 0"+ params["search"] = search+ }+ whereClause += shared.RootFilterClause("is_root", rootFilter)++ countResult, err := lit.SelectSingleNamed[models.CountResult](db.TelemetryDB,+ "SELECT COUNT(DISTINCT trace_name) AS count FROM ai_traces WHERE "+whereClause, params)+ if err != nil {+ return nil, 0, err+ }+ count := int64(0)+ if countResult != nil {+ count = int64(countResult.Count)+ }++ rows, err := lit.SelectNamed[groupedAiTraceRow](db.TelemetryDB,+ `SELECT trace_name, COUNT(*) AS total_count,+ AVG(duration) AS avg_duration,+ quantile_cont(duration, 0.50) AS p50_duration,+ quantile_cont(duration, 0.95) AS p95_duration,+ CAST(SUM(total_tokens) AS BIGINT) AS total_tokens,+ SUM(total_cost) AS total_cost,+ AVG(input_tokens) AS avg_input_tokens,+ AVG(output_tokens) AS avg_output_tokens,+ MAX(recorded_at) AS last_seen,+ MAX(is_root) AS has_root,+ MAX(CASE WHEN is_root = 0 THEN 1 ELSE 0 END) AS has_non_root+ FROM ai_traces WHERE `+whereClause+`+ GROUP BY trace_name`, params)+ if err != nil {+ return nil, 0, err+ }++ var stats []models.AiTraceStats+ for _, row := range rows {+ stats = append(stats, models.AiTraceStats{+ TraceName: row.TraceName,+ Count: row.TotalCount,+ P50Duration: time.Duration(row.P50Duration),+ P95Duration: time.Duration(row.P95Duration),+ AvgDuration: time.Duration(row.AvgDuration),+ TotalTokens: row.TotalTokens,+ TotalCost: row.TotalCost,+ AvgInputTokens: row.AvgInputTokens,+ AvgOutputTokens: row.AvgOutputTokens,+ LastSeen: row.LastSeen,+ HasRoot: row.HasRoot,+ HasNonRoot: row.HasNonRoot,+ })+ }++ orderByMap := map[string]func(i, j int) bool{+ "count": func(i, j int) bool { return stats[i].Count > stats[j].Count },+ "p50_duration": func(i, j int) bool { return stats[i].P50Duration > stats[j].P50Duration },+ "p95_duration": func(i, j int) bool { return stats[i].P95Duration > stats[j].P95Duration },+ "avg_duration": func(i, j int) bool { return stats[i].AvgDuration > stats[j].AvgDuration },+ "total_tokens": func(i, j int) bool { return stats[i].TotalTokens > stats[j].TotalTokens },+ "total_cost": func(i, j int) bool { return stats[i].TotalCost > stats[j].TotalCost },+ "last_seen": func(i, j int) bool { return stats[i].LastSeen.After(stats[j].LastSeen) },+ }++ sortFn, ok := orderByMap[orderBy]+ if !ok {+ sortFn = orderByMap["total_cost"]+ }++ if sortDirection == "asc" {+ origFn := sortFn+ sortFn = func(i, j int) bool { return !origFn(i, j) }+ }+ sort.Slice(stats, sortFn)++ offset := (page - 1) * pageSize+ end := offset + pageSize+ if offset > len(stats) {+ stats = nil+ } else if end > len(stats) {+ stats = stats[offset:]+ } else {+ stats = stats[offset:end]+ }++ return stats, count, nil+}++func (r *aiTraceRepository) FindByTraceName(ctx context.Context, projectId uuid.UUID, traceName string, fromDate, toDate time.Time, page, pageSize int, orderBy, sortDirection string) ([]models.AiTrace, int64, error) {+ params := lit.P{"project_id": projectId, "trace_name": traceName, "from": fromDate.UTC(), "to": toDate.UTC()}++ countResult, err := lit.SelectSingleNamed[models.CountResult](db.TelemetryDB,+ "SELECT COUNT(*) AS count FROM ai_traces WHERE project_id = :project_id AND trace_name = :trace_name AND recorded_at >= :from AND recorded_at <= :to",+ params)+ if err != nil {+ return nil, 0, err+ }+ count := int64(0)+ if countResult != nil {+ count = int64(countResult.Count)+ }++ offset := (page - 1) * pageSize++ allowedOrderBy := map[string]bool{+ "recorded_at": true, "duration": true, "total_tokens": true,+ "total_cost": true, "input_tokens": true, "output_tokens": true,+ }+ if !allowedOrderBy[orderBy] {+ orderBy = "recorded_at"+ }+ sortDir := "DESC"+ if sortDirection == "asc" {+ sortDir = "ASC"+ }++ rows, err := lit.SelectNamed[aiTraceRow](db.TelemetryDB,+ fmt.Sprintf(`SELECT id, project_id, recorded_at, duration, status_code,+ model, response_model, provider, operation,+ input_tokens, output_tokens, total_tokens, cached_tokens, reasoning_tokens,+ input_cost, output_cost, total_cost,+ trace_name, user_id, finish_reason, server_name, app_version,+ storage_key, attributes, distributed_trace_id, is_root+ FROM ai_traces+ WHERE project_id = :project_id AND trace_name = :trace_name AND recorded_at >= :from AND recorded_at <= :to+ ORDER BY %s %s LIMIT :limit OFFSET :offset`, orderBy, sortDir),+ lit.P{"project_id": projectId, "trace_name": traceName, "from": fromDate.UTC(), "to": toDate.UTC(), "limit": pageSize, "offset": offset})+ if err != nil {+ return nil, 0, err+ }++ traces := make([]models.AiTrace, 0, len(rows))+ for _, row := range rows {+ traces = append(traces, row.toModel())+ }++ return traces, count, nil+}++func (r *aiTraceRepository) GetTraceNameStats(ctx context.Context, projectId uuid.UUID, traceName string, start, end time.Time) (*models.AiTraceDetailStats, error) {+ durationMinutes := end.Sub(start).Minutes()+ if durationMinutes < 1 {+ durationMinutes = 1+ }++ params := lit.P{"project_id": projectId, "trace_name": traceName, "from": start.UTC(), "to": end.UTC()}++ row, err := lit.SelectSingleNamed[aiTraceDetailStatsRow](db.TelemetryDB,+ `SELECT COUNT(*) AS count,+ CASE WHEN COUNT(*) > 0 THEN AVG(duration) / 1000000.0 ELSE 0 END AS avg_duration_ms,+ COALESCE(quantile_cont(duration, 0.50) / 1000000.0, 0) AS median_duration_ms,+ COALESCE(quantile_cont(duration, 0.95) / 1000000.0, 0) AS p95_duration_ms,+ COALESCE(CAST(SUM(total_tokens) AS BIGINT), 0) AS total_tokens,+ COALESCE(SUM(total_cost), 0) AS total_cost,+ COALESCE(AVG(input_tokens), 0) AS avg_input_tokens,+ COALESCE(AVG(output_tokens), 0) AS avg_output_tokens+ FROM ai_traces+ WHERE project_id = :project_id AND trace_name = :trace_name AND recorded_at >= :from AND recorded_at <= :to`,+ params)+ if err != nil {+ return nil, err+ }++ stats := &models.AiTraceDetailStats{}+ if row != nil {+ stats.Count = row.Count+ stats.AvgDuration = row.AvgDurationMs+ stats.MedianDuration = row.MedianDurationMs+ stats.P95Duration = row.P95DurationMs+ stats.TotalTokens = row.TotalTokens+ stats.TotalCost = row.TotalCost+ stats.AvgInputTokens = row.AvgInputTokens+ stats.AvgOutputTokens = row.AvgOutputTokens+ stats.Throughput = float64(row.Count) / durationMinutes+ }++ return stats, nil+}++func (r *aiTraceRepository) FindById(ctx context.Context, projectId, traceId uuid.UUID, recordedAt *time.Time) (*models.AiTrace, error) {+ query := `SELECT id, project_id, recorded_at, duration, status_code,+ model, response_model, provider, operation,+ input_tokens, output_tokens, total_tokens, cached_tokens, reasoning_tokens,+ input_cost, output_cost, total_cost,+ trace_name, user_id, finish_reason, server_name, app_version,+ storage_key, attributes, distributed_trace_id, is_root+ FROM ai_traces+ WHERE project_id = :project_id AND id = :id`+ params := lit.P{"project_id": projectId, "id": traceId}+ if recordedAt != nil {+ from, to := shared.TraceWindowBounds(*recordedAt)+ query += ` AND recorded_at >= :from AND recorded_at <= :to`+ params["from"] = from.UTC()+ params["to"] = to.UTC()+ }+ query += ` LIMIT 1`++ row, err := lit.SelectSingleNamed[aiTraceRow](db.TelemetryDB, query, params)+ if err != nil {+ return nil, err+ }+ if row == nil {+ return nil, nil+ }+ result := row.toModel()+ return &result, nil+}++func (r *aiTraceRepository) FindByDistributedTraceId(ctx context.Context, distributedTraceId uuid.UUID, projectIds []uuid.UUID, recordedAt *time.Time) ([]models.AiTrace, error) {+ if len(projectIds) == 0 {+ return nil, nil+ }+ params := lit.P{"trace_id": distributedTraceId}+ placeholders := make([]string, len(projectIds))+ for i, pid := range projectIds {+ key := fmt.Sprintf("pid_%d", i)+ placeholders[i] = ":" + key+ params[key] = pid+ }+ query := `SELECT id, project_id, recorded_at, duration, status_code,+ model, response_model, provider, operation,+ input_tokens, output_tokens, total_tokens, cached_tokens, reasoning_tokens,+ input_cost, output_cost, total_cost,+ trace_name, user_id, finish_reason, server_name, app_version,+ storage_key, attributes, distributed_trace_id, is_root+ FROM ai_traces WHERE distributed_trace_id = :trace_id AND project_id IN (` + strings.Join(placeholders, ",") + `)`+ if recordedAt != nil {+ from, to := shared.DistributedTraceWindowBounds(*recordedAt)+ query += ` AND recorded_at >= :from AND recorded_at <= :to`+ params["from"] = from.UTC()+ params["to"] = to.UTC()+ }+ query += ` ORDER BY recorded_at ASC`++ parsedQuery, args, err := lit.ParseNamedQuery(db.Driver, query, params)+ if err != nil {+ return nil, err+ }+ sqlRows, err := db.TelemetryDB.QueryContext(ctx, parsedQuery, args...)+ if err != nil {+ return nil, err+ }+ defer sqlRows.Close()++ var traces []models.AiTrace+ for sqlRows.Next() {+ var row aiTraceRow+ if err := sqlRows.Scan(+ &row.Id, &row.ProjectId, &row.RecordedAt, &row.Duration, &row.StatusCode,+ &row.Model, &row.ResponseModel, &row.Provider, &row.Operation,+ &row.InputTokens, &row.OutputTokens, &row.TotalTokens, &row.CachedTokens, &row.ReasoningTokens,+ &row.InputCost, &row.OutputCost, &row.TotalCost,+ &row.TraceName, &row.UserId, &row.FinishReason, &row.ServerName, &row.AppVersion,+ &row.StorageKey, &row.Attributes, &row.DistributedTraceId, &row.IsRoot,+ ); err != nil {+ return nil, err+ }+ traces = append(traces, row.toModel())+ }+ return traces, nil+}++var AiTraceRepository = &aiTraceRepository{}diff --git a/backend/app/repositories/telemetry/duckdb/endpoint.repository.go b/backend/app/repositories/telemetry/duckdb/endpoint.repository.gonew file mode 100644index 00000000..42f372fb--- /dev/null+++ b/backend/app/repositories/telemetry/duckdb/endpoint.repository.go@@ -0,0 +1,925 @@+//go:build telemetry_duckdb++package duckdb++import (+ "context"+ "database/sql"+ "fmt"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/shared"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/sqlitetypes"+ "sort"+ "strings"+ "time"++ "github.com/duckdb/duckdb-go/v2"+ "github.com/google/uuid"+ "github.com/tracewayapp/lit/v2"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"+)++type endpoint struct {+ Id uuid.UUID `lit:"id"`+ ProjectId uuid.UUID `lit:"project_id"`+ Endpoint string `lit:"endpoint"`+ Duration int64 `lit:"duration"`+ RecordedAt sqlitetypes.SQLiteTime `lit:"recorded_at"`+ StatusCode int16 `lit:"status_code"`+ BodySize int32 `lit:"body_size"`+ ClientIP string `lit:"client_ip"`+ Attributes sqlitetypes.SQLiteJSONMap `lit:"attributes"`+ AppVersion string `lit:"app_version"`+ ServerName string `lit:"server_name"`+ DistributedTraceId *uuid.UUID `lit:"distributed_trace_id"`+ SpanId *uuid.UUID `lit:"span_id"`+ IsStream bool `lit:"is_stream"`+ IsRoot bool `lit:"is_root"`+}++type groupedEndpointRow struct {+ Endpoint string+ TotalCount uint64+ AvgDuration float64+ LastSeen time.Time+ OffsetMs uint32+ ServerErrorCount uint64+ ClientErrorCount uint64+ SatisfiedCount uint64+ ToleratingCount uint64+ BadCount uint64+ IsStream bool+ HasRoot bool+ HasNonRoot bool+ P50 sql.NullFloat64+ P95 sql.NullFloat64+ P99 sql.NullFloat64+}++type slowEndpointRow struct {+ OffsetMs uint32 `lit:"offset_ms"`+ Reason string `lit:"reason"`+}++type endpointMetricRow struct {+ Endpoint string `lit:"endpoint"`+ MetricValue float64 `lit:"metric_value"`+}++type endpointDetailStatsRow struct {+ Count int64 `lit:"count"`+ AvgDurationMs float64 `lit:"avg_duration_ms"`+ ErrorRate float64 `lit:"error_rate"`+ SatisfiedTolerating float64 `lit:"satisfied_tolerating"`+}++type isStreamFlagRow struct {+ IsStream bool `lit:"is_stream"`+}++func init() {+ models.ExtensionModelRegistrations = append(models.ExtensionModelRegistrations, func(driver lit.Driver) {+ lit.RegisterModel[endpoint](driver)+ lit.RegisterModel[slowEndpointRow](driver)+ lit.RegisterModel[endpointMetricRow](driver)+ lit.RegisterModel[endpointDetailStatsRow](driver)+ lit.RegisterModel[isStreamFlagRow](driver)+ })+}++func (r *endpoint) toModel() models.Endpoint {+ e := models.Endpoint{+ Id: r.Id,+ ProjectId: r.ProjectId,+ Endpoint: r.Endpoint,+ Duration: time.Duration(r.Duration),+ RecordedAt: r.RecordedAt.Time,+ StatusCode: r.StatusCode,+ BodySize: r.BodySize,+ ClientIP: r.ClientIP,+ AppVersion: r.AppVersion,+ ServerName: r.ServerName,+ DistributedTraceId: r.DistributedTraceId,+ SpanId: r.SpanId,+ IsStream: r.IsStream,+ IsRoot: r.IsRoot,+ }+ if r.Attributes != nil {+ e.Attributes = map[string]string(r.Attributes)+ }+ return e+}++// rootFilterClause returns a SQL fragment ("", " AND <col> = 1", " AND <col> = 0")+// to splice into a WHERE clause based on the rootFilter param. Accepts "all" |+// "root" | "non_root"; defaults to "all" (no filter).+type endpointRepository struct{}++func (e *endpointRepository) InsertAsync(ctx context.Context, lines []models.Endpoint) error {+ if len(lines) == 0 {+ return nil+ }++ return withAppender(ctx, "endpoints", func(appender *duckdb.Appender) {++ for _, ep := range lines {+ attributesJSON, err := attrJSON(ep.Attributes)+ if err != nil {+ captureDroppedRow("endpoints", err)+ continue+ }++ var distributedTraceId *string+ if ep.DistributedTraceId != nil {+ v := ep.DistributedTraceId.String()+ distributedTraceId = &v+ }+ var spanId *string+ if ep.SpanId != nil {+ v := ep.SpanId.String()+ spanId = &v+ }++ isStream := boolToInt(ep.IsStream)+ isRoot := boolToInt(ep.IsRoot)++ if err := appender.AppendRow(+ ep.Id.String(),+ ep.ProjectId.String(),+ ep.Endpoint,+ int64(ep.Duration),+ ep.RecordedAt.UTC(),+ int64(ep.StatusCode),+ int64(ep.BodySize),+ ep.ClientIP,+ attributesJSON,+ ep.AppVersion,+ ep.ServerName,+ nullableString(distributedTraceId),+ nullableString(spanId),+ isStream,+ isRoot,+ ); err != nil {+ captureDroppedRow("endpoints", err)+ }+ }++ })+}++func (e *endpointRepository) CountBetween(ctx context.Context, projectId uuid.UUID, start, end time.Time) (int64, error) {+ result, err := lit.SelectSingleNamed[models.CountResult](db.TelemetryDB,+ "SELECT COUNT(*) AS count FROM endpoints WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to",+ lit.P{"project_id": projectId, "from": start.UTC(), "to": end.UTC()})+ if err != nil {+ return 0, err+ }+ if result == nil {+ return 0, nil+ }+ return int64(result.Count), nil+}++func (e *endpointRepository) FindAll(ctx context.Context, projectId uuid.UUID, fromDate, toDate time.Time, page, pageSize int, orderBy string) ([]models.Endpoint, int64, error) {+ params := lit.P{"project_id": projectId, "from": fromDate.UTC(), "to": toDate.UTC()}++ countResult, err := lit.SelectSingleNamed[models.CountResult](db.TelemetryDB,+ "SELECT COUNT(*) AS count FROM endpoints WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to",+ params)+ if err != nil {+ return nil, 0, err+ }+ count := int64(0)+ if countResult != nil {+ count = int64(countResult.Count)+ }++ offset := (page - 1) * pageSize++ allowedOrderBy := map[string]bool{"recorded_at": true, "duration": true, "status_code": true, "body_size": true}+ if !allowedOrderBy[orderBy] {+ orderBy = "recorded_at"+ }++ rows, err := lit.SelectNamed[endpoint](db.TelemetryDB,+ fmt.Sprintf(`SELECT id, project_id, endpoint, duration, recorded_at, status_code, body_size, client_ip, attributes, app_version, server_name, distributed_trace_id+ FROM endpoints WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to+ ORDER BY %s DESC LIMIT :limit OFFSET :offset`, orderBy),+ lit.P{"project_id": projectId, "from": fromDate.UTC(), "to": toDate.UTC(), "limit": pageSize, "offset": offset})+ if err != nil {+ return nil, 0, err+ }++ endpoints := make([]models.Endpoint, 0, len(rows))+ for _, row := range rows {+ endpoints = append(endpoints, row.toModel())+ }++ return endpoints, count, nil+}++func (e *endpointRepository) FindGroupedByEndpoint(ctx context.Context, projectId uuid.UUID, fromDate, toDate time.Time, page, pageSize int, orderBy string, sortDirection string, search string, rootFilter string) ([]models.EndpointStats, int64, error) {+ params := lit.P{"project_id": projectId, "from": fromDate.UTC(), "to": toDate.UTC()}++ whereClause := "e.project_id = :project_id AND e.recorded_at >= :from AND e.recorded_at <= :to"+ if search != "" {+ whereClause += " AND INSTR(LOWER(e.endpoint), LOWER(:search)) > 0"+ params["search"] = search+ }+ whereClause += shared.RootFilterClause("e.is_root", rootFilter)++ groupQuery := `SELECT+ e.endpoint,+ COUNT(*) as total_count,+ AVG(e.duration) as avg_duration,+ MAX(e.recorded_at) as last_seen,+ COALESCE(s.offset_ms, 0) as offset_ms,+ CAST(SUM(CASE WHEN e.status_code >= 500 THEN 1 ELSE 0 END) AS BIGINT) as server_error_count,+ CAST(SUM(CASE WHEN e.status_code >= 400 AND e.status_code < 500 THEN 1 ELSE 0 END) AS BIGINT) as client_error_count,+ CAST(SUM(CASE WHEN e.duration <= (750000000 + COALESCE(s.offset_ms, 0) * 1000000) AND e.status_code < 500 THEN 1 ELSE 0 END) AS BIGINT) as satisfied_count,+ CAST(SUM(CASE WHEN e.duration > (750000000 + COALESCE(s.offset_ms, 0) * 1000000) AND e.duration <= (1500000000 + COALESCE(s.offset_ms, 0) * 1000000) AND e.status_code < 500 THEN 1 ELSE 0 END) AS BIGINT) as tolerating_count,+ CAST(SUM(CASE WHEN e.duration > (1500000000 + COALESCE(s.offset_ms, 0) * 1000000) OR e.status_code >= 500 THEN 1 ELSE 0 END) AS BIGINT) as bad_count,+ MAX(e.is_stream) as is_stream,+ MAX(e.is_root) as has_root,+ MAX(CASE WHEN e.is_root = 0 THEN 1 ELSE 0 END) as has_non_root,+ quantile_cont(e.duration, 0.50) FILTER (WHERE e.is_stream = 0) AS p50,+ quantile_cont(e.duration, 0.95) FILTER (WHERE e.is_stream = 0) AS p95,+ quantile_cont(e.duration, 0.99) FILTER (WHERE e.is_stream = 0) AS p99+ FROM endpoints e+ LEFT JOIN slow_endpoints s ON e.endpoint = s.endpoint AND e.project_id = s.project_id+ WHERE ` + whereClause + `+ GROUP BY e.endpoint, s.offset_ms`++ parsedQuery, args, err := lit.ParseNamedQuery(db.Driver, groupQuery, params)+ if err != nil {+ return nil, 0, err+ }++ sqlRows, err := db.TelemetryDB.QueryContext(ctx, parsedQuery, args...)+ if err != nil {+ return nil, 0, err+ }+ defer sqlRows.Close()++ var groups []groupedEndpointRow+ for sqlRows.Next() {+ var g groupedEndpointRow+ if err := sqlRows.Scan(&g.Endpoint, &g.TotalCount, &g.AvgDuration, &g.LastSeen,+ &g.OffsetMs, &g.ServerErrorCount, &g.ClientErrorCount,+ &g.SatisfiedCount, &g.ToleratingCount, &g.BadCount, &g.IsStream, &g.HasRoot, &g.HasNonRoot,+ &g.P50, &g.P95, &g.P99); err != nil {+ return nil, 0, err+ }+ groups = append(groups, g)+ }++ var stats []models.EndpointStats+ for _, g := range groups {+ lastSeen := g.LastSeen++ // Streaming endpoints are still surfaced (count, error rate, throughput),+ // but their connection lifetime is not request latency — zero out the+ // latency signals. Impact still fires on status-code-driven components+ // (server-error rate, client-error rate, volume-weighted error rate)+ // so a streaming endpoint returning lots of 5xx still ranks.+ if g.IsStream {+ stats = append(stats, models.EndpointStats{+ Endpoint: g.Endpoint,+ Count: g.TotalCount,+ LastSeen: lastSeen,+ Impact: shared.ComputeStreamImpact(g.Endpoint, g.TotalCount, g.ServerErrorCount, g.ClientErrorCount),+ ImpactReason: shared.ComputeStreamImpactReason(g.Endpoint, g.TotalCount, g.ServerErrorCount, g.ClientErrorCount),+ IsStream: true,+ HasRoot: g.HasRoot,+ HasNonRoot: g.HasNonRoot,+ })+ continue+ }++ p50 := g.P50.Float64+ p95 := g.P95.Float64+ p99 := g.P99.Float64++ impact := shared.ComputeImpactScore(g.Endpoint, g.TotalCount, g.SatisfiedCount, g.ToleratingCount, g.BadCount, g.ClientErrorCount, p99, g.OffsetMs)++ stats = append(stats, models.EndpointStats{+ Endpoint: g.Endpoint,+ Count: g.TotalCount,+ P50Duration: time.Duration(p50),+ P95Duration: time.Duration(p95),+ P99Duration: time.Duration(p99),+ AvgDuration: time.Duration(g.AvgDuration),+ LastSeen: lastSeen,+ Impact: impact,+ ImpactReason: shared.ComputeImpactReason(g.Endpoint, g.TotalCount, g.SatisfiedCount, g.ToleratingCount,+ g.BadCount, g.ClientErrorCount, p99, g.OffsetMs),+ HasRoot: g.HasRoot,+ HasNonRoot: g.HasNonRoot,+ })+ }++ sortEndpointStats(stats, orderBy, sortDirection)++ // Pagination is in-Go, so the group query already returned every group —+ // no separate COUNT(DISTINCT) scan needed.+ totalEndpoints := int64(len(stats))++ start := (page - 1) * pageSize+ if start > len(stats) {+ start = len(stats)+ }+ endIdx := start + pageSize+ if endIdx > len(stats) {+ endIdx = len(stats)+ }++ return stats[start:endIdx], totalEndpoints, nil+}++func (e *endpointRepository) FindByEndpoint(ctx context.Context, projectId uuid.UUID, endpointName string, fromDate, toDate time.Time, page, pageSize int, orderBy string, sortDirection string) ([]models.Endpoint, int64, error) {+ params := lit.P{"project_id": projectId, "endpoint": endpointName, "from": fromDate.UTC(), "to": toDate.UTC()}++ countResult, err := lit.SelectSingleNamed[models.CountResult](db.TelemetryDB,+ "SELECT COUNT(*) AS count FROM endpoints WHERE project_id = :project_id AND endpoint = :endpoint AND recorded_at >= :from AND recorded_at <= :to",+ params)+ if err != nil {+ return nil, 0, err+ }+ count := int64(0)+ if countResult != nil {+ count = int64(countResult.Count)+ }++ offset := (page - 1) * pageSize++ allowedOrderBy := map[string]bool{"recorded_at": true, "duration": true, "status_code": true, "body_size": true}+ if !allowedOrderBy[orderBy] {+ orderBy = "recorded_at"+ }++ sortDir := "DESC"+ if sortDirection == "asc" {+ sortDir = "ASC"+ }++ rows, err := lit.SelectNamed[endpoint](db.TelemetryDB,+ fmt.Sprintf(`SELECT id, project_id, endpoint, duration, recorded_at, status_code, body_size, client_ip, attributes, app_version, server_name, distributed_trace_id+ FROM endpoints WHERE project_id = :project_id AND endpoint = :endpoint AND recorded_at >= :from AND recorded_at <= :to+ ORDER BY %s %s LIMIT :limit OFFSET :offset`, orderBy, sortDir),+ lit.P{"project_id": projectId, "endpoint": endpointName, "from": fromDate.UTC(), "to": toDate.UTC(), "limit": pageSize, "offset": offset})+ if err != nil {+ return nil, 0, err+ }++ endpoints := make([]models.Endpoint, 0, len(rows))+ for _, row := range rows {+ endpoints = append(endpoints, row.toModel())+ }++ return endpoints, count, nil+}++func (e *endpointRepository) FindById(ctx context.Context, projectId, endpointId uuid.UUID, recordedAt *time.Time) (*models.Endpoint, error) {+ query := `SELECT id, project_id, endpoint, duration, recorded_at, status_code, body_size, client_ip, attributes, app_version, server_name, distributed_trace_id, span_id+ FROM endpoints WHERE project_id = :project_id AND id = :id`+ params := lit.P{"project_id": projectId, "id": endpointId}+ if recordedAt != nil {+ from, to := shared.TraceWindowBounds(*recordedAt)+ query += ` AND recorded_at >= :from AND recorded_at <= :to`+ params["from"] = from.UTC()+ params["to"] = to.UTC()+ }+ query += ` LIMIT 1`++ row, err := lit.SelectSingleNamed[endpoint](db.TelemetryDB, query, params)+ if err != nil {+ return nil, err+ }+ if row == nil {+ return nil, nil+ }+ ep := row.toModel()+ return &ep, nil+}++func (e *endpointRepository) CountByHour(ctx context.Context, projectId uuid.UUID, start, end time.Time) ([]models.TimeSeriesPoint, error) {+ results, err := lit.SelectNamed[sqlitetypes.TimeSeriesResult](db.TelemetryDB,+ `SELECT strftime(recorded_at, '%Y-%m-%d %H:00:00') as bucket, CAST(COUNT(*) AS DOUBLE) as agg_value+ FROM endpoints WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to+ GROUP BY bucket ORDER BY bucket ASC`,+ lit.P{"project_id": projectId, "from": start.UTC(), "to": end.UTC()})+ if err != nil {+ return nil, err+ }+ return sqlitetypes.TimeSeriesResultsToPoints(results), nil+}++func (e *endpointRepository) AvgDurationByHour(ctx context.Context, projectId uuid.UUID, start, end time.Time) ([]models.TimeSeriesPoint, error) {+ results, err := lit.SelectNamed[sqlitetypes.TimeSeriesResult](db.TelemetryDB,+ `SELECT strftime(recorded_at, '%Y-%m-%d %H:00:00') as bucket, AVG(duration) / 1000000.0 as agg_value+ FROM endpoints WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to AND is_stream = 0+ GROUP BY bucket ORDER BY bucket ASC`,+ lit.P{"project_id": projectId, "from": start.UTC(), "to": end.UTC()})+ if err != nil {+ return nil, err+ }+ return sqlitetypes.TimeSeriesResultsToPoints(results), nil+}++func (e *endpointRepository) ErrorRateByHour(ctx context.Context, projectId uuid.UUID, start, end time.Time) ([]models.TimeSeriesPoint, error) {+ results, err := lit.SelectNamed[sqlitetypes.TimeSeriesResult](db.TelemetryDB,+ `SELECT strftime(recorded_at, '%Y-%m-%d %H:00:00') as bucket,+ SUM(CASE WHEN status_code >= 500 THEN 1 ELSE 0 END) * 100.0 / COUNT(*) as agg_value+ FROM endpoints WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to+ GROUP BY bucket ORDER BY bucket ASC`,+ lit.P{"project_id": projectId, "from": start.UTC(), "to": end.UTC()})+ if err != nil {+ return nil, err+ }+ return sqlitetypes.TimeSeriesResultsToPoints(results), nil+}++func (e *endpointRepository) CountByInterval(ctx context.Context, projectId uuid.UUID, start, end time.Time, intervalMinutes int) ([]models.TimeSeriesPoint, error) {+ results, err := lit.SelectNamed[sqlitetypes.TimeSeriesResult](db.TelemetryDB,+ fmt.Sprintf(`SELECT strftime(%s, '%%Y-%%m-%%d %%H:%%M:%%S') as bucket, CAST(COUNT(*) AS DOUBLE) as agg_value+ FROM endpoints WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to+ GROUP BY bucket ORDER BY bucket ASC`, timeBucketExpr("recorded_at", intervalMinutes*60)),+ lit.P{"project_id": projectId, "from": start.UTC(), "to": end.UTC()})+ if err != nil {+ return nil, err+ }+ return sqlitetypes.TimeSeriesResultsToPoints(results), nil+}++func (e *endpointRepository) AvgDurationByInterval(ctx context.Context, projectId uuid.UUID, start, end time.Time, intervalMinutes int) ([]models.TimeSeriesPoint, error) {+ results, err := lit.SelectNamed[sqlitetypes.TimeSeriesResult](db.TelemetryDB,+ fmt.Sprintf(`SELECT strftime(%s, '%%Y-%%m-%%d %%H:%%M:%%S') as bucket, AVG(duration) / 1000000.0 as agg_value+ FROM endpoints WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to AND is_stream = 0+ GROUP BY bucket ORDER BY bucket ASC`, timeBucketExpr("recorded_at", intervalMinutes*60)),+ lit.P{"project_id": projectId, "from": start.UTC(), "to": end.UTC()})+ if err != nil {+ return nil, err+ }+ return sqlitetypes.TimeSeriesResultsToPoints(results), nil+}++func (e *endpointRepository) ErrorRateByInterval(ctx context.Context, projectId uuid.UUID, start, end time.Time, intervalMinutes int) ([]models.TimeSeriesPoint, error) {+ results, err := lit.SelectNamed[sqlitetypes.TimeSeriesResult](db.TelemetryDB,+ fmt.Sprintf(`SELECT strftime(%s, '%%Y-%%m-%%d %%H:%%M:%%S') as bucket,+ SUM(CASE WHEN status_code >= 500 THEN 1 ELSE 0 END) * 100.0 / COUNT(*) as agg_value+ FROM endpoints WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to+ GROUP BY bucket ORDER BY bucket ASC`, timeBucketExpr("recorded_at", intervalMinutes*60)),+ lit.P{"project_id": projectId, "from": start.UTC(), "to": end.UTC()})+ if err != nil {+ return nil, err+ }+ return sqlitetypes.TimeSeriesResultsToPoints(results), nil+}++func (e *endpointRepository) FindWorstEndpoints(ctx context.Context, projectId uuid.UUID, start, end time.Time, limit int) ([]models.EndpointStats, error) {+ params := lit.P{"project_id": projectId, "from": start.UTC(), "to": end.UTC()}++ groupQuery := `SELECT+ e.endpoint,+ COUNT(*) as total_count,+ AVG(e.duration) as avg_duration,+ MAX(e.recorded_at) as last_seen,+ COALESCE(s.offset_ms, 0) as offset_ms,+ CAST(SUM(CASE WHEN e.status_code >= 500 THEN 1 ELSE 0 END) AS BIGINT) as server_error_count,+ CAST(SUM(CASE WHEN e.status_code >= 400 AND e.status_code < 500 THEN 1 ELSE 0 END) AS BIGINT) as client_error_count,+ CAST(SUM(CASE WHEN e.duration <= (750000000 + COALESCE(s.offset_ms, 0) * 1000000) AND e.status_code < 500 THEN 1 ELSE 0 END) AS BIGINT) as satisfied_count,+ CAST(SUM(CASE WHEN e.duration > (750000000 + COALESCE(s.offset_ms, 0) * 1000000) AND e.duration <= (1500000000 + COALESCE(s.offset_ms, 0) * 1000000) AND e.status_code < 500 THEN 1 ELSE 0 END) AS BIGINT) as tolerating_count,+ CAST(SUM(CASE WHEN e.duration > (1500000000 + COALESCE(s.offset_ms, 0) * 1000000) OR e.status_code >= 500 THEN 1 ELSE 0 END) AS BIGINT) as bad_count,+ MAX(e.is_stream) as is_stream,+ quantile_cont(e.duration, 0.50) FILTER (WHERE e.is_stream = 0) AS p50,+ quantile_cont(e.duration, 0.95) FILTER (WHERE e.is_stream = 0) AS p95,+ quantile_cont(e.duration, 0.99) FILTER (WHERE e.is_stream = 0) AS p99+ FROM endpoints e+ LEFT JOIN slow_endpoints s ON e.endpoint = s.endpoint AND e.project_id = s.project_id+ WHERE e.project_id = :project_id AND e.recorded_at >= :from AND e.recorded_at <= :to AND e.is_stream = 0+ GROUP BY e.endpoint, s.offset_ms`++ parsedQuery, args, err := lit.ParseNamedQuery(db.Driver, groupQuery, params)+ if err != nil {+ return nil, err+ }++ sqlRows, err := db.TelemetryDB.QueryContext(ctx, parsedQuery, args...)+ if err != nil {+ return nil, err+ }+ defer sqlRows.Close()++ var groups []groupedEndpointRow+ for sqlRows.Next() {+ var g groupedEndpointRow+ if err := sqlRows.Scan(&g.Endpoint, &g.TotalCount, &g.AvgDuration, &g.LastSeen,+ &g.OffsetMs, &g.ServerErrorCount, &g.ClientErrorCount,+ &g.SatisfiedCount, &g.ToleratingCount, &g.BadCount, &g.IsStream,+ &g.P50, &g.P95, &g.P99); err != nil {+ return nil, err+ }+ groups = append(groups, g)+ }++ var stats []models.EndpointStats+ for _, g := range groups {+ p50 := g.P50.Float64+ p95 := g.P95.Float64+ p99 := g.P99.Float64++ impact := shared.ComputeImpactScore(g.Endpoint, g.TotalCount, g.SatisfiedCount, g.ToleratingCount, g.BadCount, g.ClientErrorCount, p99, g.OffsetMs)++ lastSeen := g.LastSeen++ stats = append(stats, models.EndpointStats{+ Endpoint: g.Endpoint,+ Count: g.TotalCount,+ P50Duration: time.Duration(p50),+ P95Duration: time.Duration(p95),+ P99Duration: time.Duration(p99),+ AvgDuration: time.Duration(g.AvgDuration),+ LastSeen: lastSeen,+ Impact: impact,+ ImpactReason: shared.ComputeImpactReason(g.Endpoint, g.TotalCount, g.SatisfiedCount, g.ToleratingCount,+ g.BadCount, g.ClientErrorCount, p99, g.OffsetMs),+ })+ }++ sort.Slice(stats, func(i, j int) bool {+ return stats[i].Impact > stats[j].Impact+ })++ if limit > 0 && limit < len(stats) {+ stats = stats[:limit]+ }++ return stats, nil+}++func (e *endpointRepository) GetEndpointStats(ctx context.Context, projectId uuid.UUID, endpoint string, start, end time.Time) (*models.EndpointDetailStats, error) {+ params := lit.P{"project_id": projectId, "endpoint": endpoint, "from": start.UTC(), "to": end.UTC()}++ durationMinutes := end.Sub(start).Minutes()+ if durationMinutes < 1 {+ durationMinutes = 1+ }++ row, err := lit.SelectSingleNamed[endpointDetailStatsRow](db.TelemetryDB,+ `SELECT+ COUNT(*) as count,+ CASE WHEN COUNT(*) > 0 THEN AVG(duration) / 1000000.0 ELSE 0 END as avg_duration_ms,+ CASE WHEN COUNT(*) > 0 THEN SUM(CASE WHEN status_code >= 500 THEN 1 ELSE 0 END) * 100.0 / COUNT(*) ELSE 0 END as error_rate,+ COALESCE(SUM(CASE WHEN duration <= 500000000 AND status_code < 500 THEN 1 ELSE 0 END) ++ SUM(CASE WHEN duration > 500000000 AND duration <= 2000000000 AND status_code < 500 THEN 1 ELSE 0 END) * 0.5, 0) as satisfied_tolerating+ FROM endpoints WHERE project_id = :project_id AND endpoint = :endpoint AND recorded_at >= :from AND recorded_at <= :to`,+ params)+ if err != nil {+ return nil, err+ }+ if row == nil {+ return &models.EndpointDetailStats{}, nil+ }++ isStreamRow, err := lit.SelectSingleNamed[isStreamFlagRow](db.TelemetryDB,+ `SELECT COALESCE(MAX(is_stream), 0) as is_stream FROM endpoints WHERE project_id = :project_id AND endpoint = :endpoint AND recorded_at >= :from AND recorded_at <= :to`,+ params)+ if err != nil {+ return nil, err+ }+ isStream := isStreamRow != nil && isStreamRow.IsStream++ var stats models.EndpointDetailStats+ stats.Count = row.Count+ stats.ErrorRate = row.ErrorRate+ stats.Throughput = float64(row.Count) / durationMinutes+ stats.IsStream = isStream++ if !isStream {+ stats.AvgDuration = row.AvgDurationMs+ if row.Count > 0 {+ stats.Apdex = row.SatisfiedTolerating / float64(row.Count)+ }++ pctQuery, pctArgs, err := lit.ParseNamedQuery(db.Driver,+ `SELECT quantile_cont(duration, 0.5) AS p50, quantile_cont(duration, 0.95) AS p95, quantile_cont(duration, 0.99) AS p99+ FROM endpoints WHERE project_id = :project_id AND endpoint = :endpoint AND recorded_at >= :from AND recorded_at <= :to AND is_stream = 0`,+ params)+ if err != nil {+ return nil, err+ }++ var p50, p95, p99 sql.NullFloat64+ if err := db.TelemetryDB.QueryRowContext(ctx, pctQuery, pctArgs...).Scan(&p50, &p95, &p99); err != nil {+ return nil, err+ }++ stats.MedianDuration = p50.Float64 / 1000000.0+ stats.P95Duration = p95.Float64 / 1000000.0+ stats.P99Duration = p99.Float64 / 1000000.0+ }++ return &stats, nil+}++func (e *endpointRepository) GetEndpointStackedChart(ctx context.Context, projectId uuid.UUID, start, end time.Time, intervalMinutes int, metricType string) (*models.EndpointStackedChartResponse, error) {+ params := lit.P{"project_id": projectId, "from": start.UTC(), "to": end.UTC()}++ topEndpoints, err := getTopEndpointsByMetric(ctx, projectId, start, end, metricType)+ if err != nil {+ return nil, err+ }++ if len(topEndpoints) == 0 {+ return &models.EndpointStackedChartResponse{+ Endpoints: []string{},+ Series: []models.EndpointTimeSeriesPoint{},+ }, nil+ }++ secs := intervalMinutes * 60++ if metricType == "p50" || metricType == "p95" || metricType == "p99" || metricType == "" {+ return e.getStackedChartWithPercentiles(ctx, projectId, start, end, secs, topEndpoints, metricType)+ }++ caseExpr := "CASE "+ for i, ep := range topEndpoints {+ key := fmt.Sprintf("ep_%d", i)+ caseExpr += fmt.Sprintf("WHEN endpoint = :%s THEN :%s ", key, key)+ params[key] = ep+ }+ caseExpr += "ELSE 'Other' END"++ var metricExpr string+ switch metricType {+ case "total_time":+ metricExpr = "COUNT(*) * AVG(duration) / 1000000.0"+ default:+ metricExpr = "AVG(duration) / 1000000.0"+ }++ timeSeriesQuery := fmt.Sprintf(`SELECT+ %s as bucket,+ %s as endpoint_category,+ %s as metric_value+ FROM endpoints+ WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to AND is_stream = 0+ GROUP BY bucket, endpoint_category+ ORDER BY bucket ASC, endpoint_category ASC`, timeBucketExpr("recorded_at", secs), caseExpr, metricExpr)++ parsedQuery, args, err := lit.ParseNamedQuery(db.Driver, timeSeriesQuery, params)+ if err != nil {+ return nil, err+ }++ sqlRows, err := db.TelemetryDB.QueryContext(ctx, parsedQuery, args...)+ if err != nil {+ return nil, err+ }+ defer sqlRows.Close()++ var series []models.EndpointTimeSeriesPoint+ for sqlRows.Next() {+ var p models.EndpointTimeSeriesPoint+ var bucket time.Time+ if err := sqlRows.Scan(&bucket, &p.Endpoint, &p.Value); err != nil {+ return nil, err+ }+ p.Timestamp = bucket+ series = append(series, p)+ }++ endpointSet := make(map[string]bool)+ for _, p := range series {+ endpointSet[p.Endpoint] = true+ }++ finalEndpoints := make([]string, 0, len(topEndpoints)+1)+ finalEndpoints = append(finalEndpoints, topEndpoints...)+ if endpointSet["Other"] {+ finalEndpoints = append(finalEndpoints, "Other")+ }++ return &models.EndpointStackedChartResponse{+ Endpoints: finalEndpoints,+ Series: series,+ }, nil+}++func (e *endpointRepository) getStackedChartWithPercentiles(ctx context.Context, projectId uuid.UUID, start, end time.Time, bucketSecs int, topEndpoints []string, metricType string) (*models.EndpointStackedChartResponse, error) {+ percentile := 0.5+ switch metricType {+ case "p95":+ percentile = 0.95+ case "p99":+ percentile = 0.99+ }++ params := lit.P{"project_id": projectId, "from": start.UTC(), "to": end.UTC()}++ caseExpr := "CASE "+ for i, ep := range topEndpoints {+ key := fmt.Sprintf("ep_%d", i)+ caseExpr += fmt.Sprintf("WHEN endpoint = :%s THEN :%s ", key, key)+ params[key] = ep+ }+ caseExpr += "ELSE 'Other' END"++ query := fmt.Sprintf(`SELECT+ %s as bucket,+ %s as endpoint_category,+ quantile_cont(duration, %g) / 1000000.0 as metric_value+ FROM endpoints+ WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to AND is_stream = 0+ GROUP BY bucket, endpoint_category+ ORDER BY bucket ASC, endpoint_category ASC`, timeBucketExpr("recorded_at", bucketSecs), caseExpr, percentile)++ parsedQuery, args, err := lit.ParseNamedQuery(db.Driver, query, params)+ if err != nil {+ return nil, err+ }++ sqlRows, err := db.TelemetryDB.QueryContext(ctx, parsedQuery, args...)+ if err != nil {+ return nil, err+ }+ defer sqlRows.Close()++ var series []models.EndpointTimeSeriesPoint+ for sqlRows.Next() {+ var bucket time.Time+ var category string+ var value float64+ if err := sqlRows.Scan(&bucket, &category, &value); err != nil {+ return nil, err+ }+ series = append(series, models.EndpointTimeSeriesPoint{+ Timestamp: bucket.UTC(),+ Endpoint: category,+ Value: value,+ })+ }++ endpointSet := make(map[string]bool)+ for _, p := range series {+ endpointSet[p.Endpoint] = true+ }++ finalEndpoints := make([]string, 0, len(topEndpoints)+1)+ finalEndpoints = append(finalEndpoints, topEndpoints...)+ if endpointSet["Other"] {+ finalEndpoints = append(finalEndpoints, "Other")+ }++ return &models.EndpointStackedChartResponse{+ Endpoints: finalEndpoints,+ Series: series,+ }, nil+}++func (e *endpointRepository) GetSlowEndpoint(ctx context.Context, projectId uuid.UUID, endpoint string) (uint32, string, error) {+ result, err := lit.SelectSingleNamed[slowEndpointRow](db.TelemetryDB,+ "SELECT offset_ms, reason FROM slow_endpoints WHERE project_id = :project_id AND endpoint = :endpoint",+ lit.P{"project_id": projectId, "endpoint": endpoint})+ if err != nil {+ return 0, "", err+ }+ if result == nil {+ return 0, "", sql.ErrNoRows+ }+ return result.OffsetMs, result.Reason, nil+}++func (e *endpointRepository) UpsertSlowEndpoint(ctx context.Context, projectId uuid.UUID, endpoint string, offsetMs uint32, reason string) error {+ query, args, err := lit.ParseNamedQuery(db.Driver,+ "INSERT INTO slow_endpoints (project_id, endpoint, offset_ms, reason) VALUES (:project_id, :endpoint, :offset_ms, :reason) ON CONFLICT (project_id, endpoint) DO UPDATE SET offset_ms = excluded.offset_ms, reason = excluded.reason",+ lit.P{"project_id": projectId, "endpoint": endpoint, "offset_ms": offsetMs, "reason": reason})+ if err != nil {+ return err+ }+ if _, err := db.TelemetryDB.ExecContext(ctx, query, args...); err != nil {+ return err+ }+ return nil+}++// --- helpers ---++func sortEndpointStats(stats []models.EndpointStats, orderBy string, sortDirection string) {+ desc := sortDirection != "asc"++ sort.Slice(stats, func(i, j int) bool {+ var less bool+ switch orderBy {+ case "count":+ less = stats[i].Count < stats[j].Count+ case "p50_duration":+ less = stats[i].P50Duration < stats[j].P50Duration+ case "p95_duration":+ less = stats[i].P95Duration < stats[j].P95Duration+ case "p99_duration":+ less = stats[i].P99Duration < stats[j].P99Duration+ case "avg_duration":+ less = stats[i].AvgDuration < stats[j].AvgDuration+ case "last_seen":+ less = stats[i].LastSeen.Before(stats[j].LastSeen)+ default:+ less = stats[i].Impact < stats[j].Impact+ }+ if desc {+ return !less+ }+ return less+ })+}++func getTopEndpointsByMetric(ctx context.Context, projectId uuid.UUID, from, to time.Time, metricType string) ([]string, error) {+ params := lit.P{"project_id": projectId, "from": from.UTC(), "to": to.UTC()}++ if metricType == "total_time" {+ results, err := lit.SelectNamed[endpointMetricRow](db.TelemetryDB,+ `SELECT endpoint, COUNT(*) * AVG(duration) / 1000000.0 as metric_value+ FROM endpoints WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to AND is_stream = 0+ GROUP BY endpoint ORDER BY metric_value DESC LIMIT 5`,+ params)+ if err != nil {+ return nil, err+ }++ endpoints := make([]string, 0, len(results))+ for _, r := range results {+ endpoints = append(endpoints, r.Endpoint)+ }+ return endpoints, nil+ }++ percentile := 0.5+ switch metricType {+ case "p95":+ percentile = 0.95+ case "p99":+ percentile = 0.99+ }++ results, err := lit.SelectNamed[endpointMetricRow](db.TelemetryDB,+ fmt.Sprintf(`SELECT endpoint, quantile_cont(duration, %g) / 1000000.0 as metric_value+ FROM endpoints WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to AND is_stream = 0+ GROUP BY endpoint ORDER BY metric_value DESC LIMIT 5`, percentile),+ params)+ if err != nil {+ return nil, err+ }++ endpoints := make([]string, 0, len(results))+ for _, r := range results {+ endpoints = append(endpoints, r.Endpoint)+ }+ return endpoints, nil+}++func (e *endpointRepository) FindByDistributedTraceId(ctx context.Context, distributedTraceId uuid.UUID, projectIds []uuid.UUID, recordedAt *time.Time) ([]models.Endpoint, error) {+ if len(projectIds) == 0 {+ return nil, nil+ }+ params := lit.P{"trace_id": distributedTraceId}+ placeholders := make([]string, len(projectIds))+ for i, pid := range projectIds {+ key := fmt.Sprintf("pid_%d", i)+ placeholders[i] = ":" + key+ params[key] = pid+ }+ query := `SELECT id, project_id, endpoint, duration, recorded_at, status_code, body_size, client_ip, attributes, app_version, server_name, distributed_trace_id+ FROM endpoints WHERE distributed_trace_id = :trace_id AND project_id IN (` + strings.Join(placeholders, ",") + `)`+ if recordedAt != nil {+ from, to := shared.DistributedTraceWindowBounds(*recordedAt)+ query += ` AND recorded_at >= :from AND recorded_at <= :to`+ params["from"] = from.UTC()+ params["to"] = to.UTC()+ }+ query += ` ORDER BY recorded_at ASC`++ parsedQuery, args, err := lit.ParseNamedQuery(db.Driver, query, params)+ if err != nil {+ return nil, err+ }++ sqlRows, err := db.TelemetryDB.QueryContext(ctx, parsedQuery, args...)+ if err != nil {+ return nil, err+ }+ defer sqlRows.Close()++ var endpoints []models.Endpoint+ for sqlRows.Next() {+ var row endpoint+ if err := sqlRows.Scan(&row.Id, &row.ProjectId, &row.Endpoint, &row.Duration, &row.RecordedAt,+ &row.StatusCode, &row.BodySize, &row.ClientIP, &row.Attributes, &row.AppVersion, &row.ServerName, &row.DistributedTraceId); err != nil {+ return nil, err+ }+ endpoints = append(endpoints, row.toModel())+ }+ return endpoints, nil+}++var EndpointRepository = &endpointRepository{}diff --git a/backend/app/repositories/telemetry/duckdb/exception_stack_trace.repository.go b/backend/app/repositories/telemetry/duckdb/exception_stack_trace.repository.gonew file mode 100644index 00000000..8335c4c9--- /dev/null+++ b/backend/app/repositories/telemetry/duckdb/exception_stack_trace.repository.go@@ -0,0 +1,571 @@+//go:build telemetry_duckdb++package duckdb++import (+ "context"+ "database/sql"+ "fmt"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/shared"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/sqlitetypes"+ "strings"+ "time"++ "github.com/duckdb/duckdb-go/v2"+ "github.com/google/uuid"+ "github.com/tracewayapp/lit/v2"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"+)++type exceptionRow struct {+ Id uuid.UUID `lit:"id"`+ ProjectId uuid.UUID `lit:"project_id"`+ TraceId *uuid.UUID `lit:"trace_id"`+ TraceType string `lit:"trace_type"`+ ExceptionHash string `lit:"exception_hash"`+ StackTrace string `lit:"stack_trace"`+ RecordedAt sqlitetypes.SQLiteTime `lit:"recorded_at"`+ Attributes sqlitetypes.SQLiteJSONMap `lit:"attributes"`+ AppVersion string `lit:"app_version"`+ ServerName string `lit:"server_name"`+ IsMessage bool `lit:"is_message"`+ DistributedTraceId *uuid.UUID `lit:"distributed_trace_id"`+ SessionId *uuid.UUID `lit:"session_id"`+}++type exceptionRowNaming struct{ lit.DefaultDbNamingStrategy }++func (exceptionRowNaming) GetTableNameFromStructName(string) string {+ return "exception_stack_traces"+}++// In DuckDB the aggregated timestamp/count columns come back as native+// TIMESTAMP/BIGINT values, so these fields scan via sqlitetypes.SQLiteTime / sql.NullTime+// rather than the raw strings the SQLite driver returns.+type exceptionGroupRow struct {+ ExceptionHash string `lit:"exception_hash"`+ StackTrace string `lit:"stack_trace"`+ LastSeen sqlitetypes.SQLiteTime `lit:"last_seen"`+ FirstSeen sqlitetypes.SQLiteTime `lit:"first_seen"`+ Count uint64 `lit:"count"`+ MaxArchivedAt sql.NullTime `lit:"max_archived_at"`+ Total int64 `lit:"total"`+}++type exceptionTrendRow struct {+ Hash string `lit:"exception_hash"`+ Hour sqlitetypes.SQLiteTime `lit:"hour"`+ Count uint64 `lit:"count"`+}++type exceptionBucketRow struct {+ Bucket sqlitetypes.SQLiteTime `lit:"bucket"`+ Value float64 `lit:"agg_value"`+}++func init() {+ models.ExtensionModelRegistrations = append(models.ExtensionModelRegistrations, func(driver lit.Driver) {+ lit.RegisterModelWithNaming[exceptionRow](driver, exceptionRowNaming{})+ lit.RegisterModel[exceptionGroupRow](driver)+ lit.RegisterModel[exceptionTrendRow](driver)+ lit.RegisterModel[exceptionBucketRow](driver)+ })+}++func (r *exceptionRow) toModel() models.ExceptionStackTrace {+ est := models.ExceptionStackTrace{+ Id: r.Id,+ ProjectId: r.ProjectId,+ TraceId: r.TraceId,+ TraceType: r.TraceType,+ ExceptionHash: r.ExceptionHash,+ StackTrace: r.StackTrace,+ RecordedAt: r.RecordedAt.Time,+ AppVersion: r.AppVersion,+ ServerName: r.ServerName,+ IsMessage: r.IsMessage,+ DistributedTraceId: r.DistributedTraceId,+ SessionId: r.SessionId,+ }+ if r.Attributes != nil {+ est.Attributes = map[string]string(r.Attributes)+ }+ return est+}++func exceptionBucketsToPoints(rows []*exceptionBucketRow) []models.TimeSeriesPoint {+ points := make([]models.TimeSeriesPoint, 0, len(rows))+ for _, row := range rows {+ points = append(points, models.TimeSeriesPoint{Timestamp: row.Bucket.Time, Value: row.Value})+ }+ return points+}++type exceptionStackTraceRepository struct{}++func (e *exceptionStackTraceRepository) InsertAsync(ctx context.Context, lines []models.ExceptionStackTrace) error {+ if len(lines) == 0 {+ return nil+ }++ return withAppender(ctx, "exception_stack_traces", func(appender *duckdb.Appender) {++ for _, est := range lines {+ traceType := est.TraceType+ if traceType == "" {+ traceType = "endpoint"+ }++ attributesJSON, err := attrJSON(est.Attributes)+ if err != nil {+ captureDroppedRow("exception_stack_traces", err)+ continue+ }++ var traceId *string+ if est.TraceId != nil {+ v := est.TraceId.String()+ traceId = &v+ }+ var distributedTraceId *string+ if est.DistributedTraceId != nil {+ v := est.DistributedTraceId.String()+ distributedTraceId = &v+ }+ var sessionId *string+ if est.SessionId != nil {+ v := est.SessionId.String()+ sessionId = &v+ }++ isMessage := boolToInt(est.IsMessage)++ if err := appender.AppendRow(+ est.Id.String(),+ est.ProjectId.String(),+ nullableString(traceId),+ traceType,+ est.ExceptionHash,+ est.StackTrace,+ est.RecordedAt.UTC(),+ attributesJSON,+ est.AppVersion,+ est.ServerName,+ isMessage,+ nullableString(distributedTraceId),+ nullableString(sessionId),+ ); err != nil {+ captureDroppedRow("exception_stack_traces", err)+ }+ }++ })+}++func (e *exceptionStackTraceRepository) CountBetween(ctx context.Context, projectId uuid.UUID, start, end time.Time) (int64, error) {+ result, err := lit.SelectSingleNamed[models.CountResult](db.TelemetryDB,+ "SELECT COUNT(*) AS count FROM exception_stack_traces WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to",+ lit.P{"project_id": projectId, "from": start.UTC(), "to": end.UTC()})+ if err != nil {+ return 0, err+ }+ if result == nil {+ return 0, nil+ }+ return int64(result.Count), nil+}++func (e *exceptionStackTraceRepository) FindGrouped(ctx context.Context, projectId uuid.UUID, fromDate, toDate time.Time, page, pageSize int, orderBy string, search string, searchType string, includeArchived bool) ([]models.ExceptionGroup, int64, error) {+ offset := (page - 1) * pageSize++ sortDirection := "DESC"+ if strings.HasSuffix(orderBy, "_asc") {+ orderBy = strings.TrimSuffix(orderBy, "_asc")+ sortDirection = "ASC"+ }++ allowedOrderBy := map[string]bool{"last_seen": true, "first_seen": true, "count": true}+ if !allowedOrderBy[orderBy] {+ orderBy = "count"+ }++ params := lit.P{"project_id": projectId, "from": fromDate.UTC(), "to": toDate.UTC()}++ whereClause := "e.project_id = :project_id AND e.recorded_at >= :from AND e.recorded_at <= :to"+ if search != "" {+ whereClause += " AND INSTR(LOWER(e.stack_trace), LOWER(:search)) > 0"+ params["search"] = search+ }+ if searchType == "issues" {+ whereClause += " AND e.is_message = 0"+ } else if searchType == "messages" {+ whereClause += " AND e.is_message = 1"+ }++ havingClause := ""+ if !includeArchived {+ havingClause = " HAVING max_archived_at IS NULL OR MAX(e.recorded_at) > max_archived_at"+ }++ archiveSubquery := `LEFT JOIN (+ SELECT exception_hash, MAX(archived_at) as archived_at+ FROM archived_exceptions WHERE project_id = :archive_project_id+ GROUP BY exception_hash+ ) a ON e.exception_hash = a.exception_hash`+ params["archive_project_id"] = projectId++ // COUNT(*) OVER () is evaluated on the post-GROUP BY/HAVING rows before+ // LIMIT, so one scan yields both the page and the total group count.+ fullQuery := `SELECT e.exception_hash, ANY_VALUE(e.stack_trace) as stack_trace, MAX(e.recorded_at) as last_seen, MIN(e.recorded_at) as first_seen, COUNT(*) as count, MAX(a.archived_at) as max_archived_at, COUNT(*) OVER () as total+ FROM exception_stack_traces e ` + archiveSubquery + `+ WHERE ` + whereClause + `+ GROUP BY e.exception_hash` + havingClause + `+ ORDER BY ` + orderBy + ` ` + sortDirection + ` LIMIT :limit OFFSET :offset`+ params["limit"] = pageSize+ params["offset"] = offset++ groupRows, err := lit.SelectNamed[exceptionGroupRow](db.TelemetryDB, fullQuery, params)+ if err != nil {+ return nil, 0, err+ }++ count := int64(0)+ if len(groupRows) > 0 {+ count = groupRows[0].Total+ } else if page > 1 {+ // An offset past the last group returns no rows and thus no window+ // total; only then fall back to a separate count scan.+ countQuery := `SELECT COUNT(*) AS count FROM (+ SELECT e.exception_hash, MAX(a.archived_at) as max_archived_at+ FROM exception_stack_traces e ` + archiveSubquery + `+ WHERE ` + whereClause + `+ GROUP BY e.exception_hash` + havingClause + `) AS sub`++ countResult, err := lit.SelectSingleNamed[models.CountResult](db.TelemetryDB, countQuery, params)+ if err != nil {+ return nil, 0, err+ }+ if countResult != nil {+ count = int64(countResult.Count)+ }+ }++ groups := make([]models.ExceptionGroup, 0, len(groupRows))+ for _, g := range groupRows {+ groups = append(groups, models.ExceptionGroup{+ ExceptionHash: g.ExceptionHash,+ StackTrace: g.StackTrace,+ LastSeen: g.LastSeen.Time,+ FirstSeen: g.FirstSeen.Time,+ Count: g.Count,+ })+ }++ return groups, count, nil+}++func (e *exceptionStackTraceRepository) FindByHash(ctx context.Context, projectId uuid.UUID, exceptionHash string, page, pageSize int) (*models.ExceptionGroup, []models.ExceptionStackTrace, int64, error) {+ offset := (page - 1) * pageSize+ params := lit.P{"project_id": projectId, "exception_hash": exceptionHash}++ groupRow, err := lit.SelectSingleNamed[exceptionGroupRow](db.TelemetryDB,+ `SELECT exception_hash, ANY_VALUE(stack_trace) as stack_trace, MAX(recorded_at) as last_seen, MIN(recorded_at) as first_seen, COUNT(*) as count, NULL as max_archived_at+ FROM exception_stack_traces WHERE project_id = :project_id AND exception_hash = :exception_hash+ GROUP BY exception_hash`,+ params)+ if err != nil {+ return nil, nil, 0, err+ }+ if groupRow == nil {+ return nil, nil, 0, nil+ }++ group := &models.ExceptionGroup{+ ExceptionHash: groupRow.ExceptionHash,+ StackTrace: groupRow.StackTrace,+ LastSeen: groupRow.LastSeen.Time,+ FirstSeen: groupRow.FirstSeen.Time,+ Count: groupRow.Count,+ }++ rows, err := lit.SelectNamed[exceptionRow](db.TelemetryDB,+ `SELECT id, project_id, trace_id, trace_type, exception_hash, stack_trace, recorded_at, attributes, app_version, server_name, is_message, distributed_trace_id, session_id+ FROM exception_stack_traces WHERE project_id = :project_id AND exception_hash = :exception_hash+ ORDER BY recorded_at DESC LIMIT :limit OFFSET :offset`,+ lit.P{"project_id": projectId, "exception_hash": exceptionHash, "limit": pageSize, "offset": offset})+ if err != nil {+ return nil, nil, 0, err+ }++ occurrences := make([]models.ExceptionStackTrace, 0, len(rows))+ for _, row := range rows {+ occurrences = append(occurrences, row.toModel())+ }++ return group, occurrences, int64(group.Count), nil+}++func (e *exceptionStackTraceRepository) CountByHour(ctx context.Context, projectId uuid.UUID, start, end time.Time) ([]models.TimeSeriesPoint, error) {+ results, err := lit.SelectNamed[exceptionBucketRow](db.TelemetryDB,+ `SELECT `+timeBucketExpr("recorded_at", 3600)+` as bucket, CAST(COUNT(*) AS DOUBLE) as agg_value+ FROM exception_stack_traces WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to+ GROUP BY bucket ORDER BY bucket ASC`,+ lit.P{"project_id": projectId, "from": start.UTC(), "to": end.UTC()})+ if err != nil {+ return nil, err+ }+ return exceptionBucketsToPoints(results), nil+}++func (e *exceptionStackTraceRepository) CountByInterval(ctx context.Context, projectId uuid.UUID, start, end time.Time, intervalMinutes int) ([]models.TimeSeriesPoint, error) {+ results, err := lit.SelectNamed[exceptionBucketRow](db.TelemetryDB,+ `SELECT `+timeBucketExpr("recorded_at", intervalMinutes*60)+` as bucket, CAST(COUNT(*) AS DOUBLE) as agg_value+ FROM exception_stack_traces WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to+ GROUP BY bucket ORDER BY bucket ASC`,+ lit.P{"project_id": projectId, "from": start.UTC(), "to": end.UTC()})+ if err != nil {+ return nil, err+ }+ return exceptionBucketsToPoints(results), nil+}++func (e *exceptionStackTraceRepository) GetHourlyTrendForHashes(ctx context.Context, projectId uuid.UUID, hashes []string, start, end time.Time) (map[string][]models.ExceptionTrendPoint, error) {+ if len(hashes) == 0 {+ return make(map[string][]models.ExceptionTrendPoint), nil+ }++ params := lit.P{"project_id": projectId, "from": start.UTC(), "to": end.UTC()}+ placeholders := make([]string, len(hashes))+ for i, h := range hashes {+ key := fmt.Sprintf("hash_%d", i)+ placeholders[i] = ":" + key+ params[key] = h+ }++ query := `SELECT exception_hash, ` + timeBucketExpr("recorded_at", 3600) + ` as hour, COUNT(*) as count+ FROM exception_stack_traces+ WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to+ AND exception_hash IN (` + strings.Join(placeholders, ",") + `)+ GROUP BY exception_hash, hour ORDER BY exception_hash, hour ASC`++ trendRows, err := lit.SelectNamed[exceptionTrendRow](db.TelemetryDB, query, params)+ if err != nil {+ return nil, err+ }++ result := make(map[string][]models.ExceptionTrendPoint)+ for _, row := range trendRows {+ result[row.Hash] = append(result[row.Hash], models.ExceptionTrendPoint{+ Timestamp: row.Hour.Time,+ Count: row.Count,+ })+ }++ return result, nil+}++func (e *exceptionStackTraceRepository) ArchiveByHashes(ctx context.Context, projectId uuid.UUID, hashes []string) error {+ if len(hashes) == 0 {+ return nil+ }++ // One transaction for the whole batch — per-statement autocommit costs a+ // WAL checkpoint per hash on DuckDB (see InsertStacksAsync).+ tx, err := db.TelemetryDB.BeginTx(ctx, nil)+ if err != nil {+ return err+ }+ defer tx.Rollback()++ now := time.Now().UTC()+ for _, hash := range hashes {+ query, args, err := lit.ParseNamedQuery(db.Driver,+ "INSERT INTO archived_exceptions (project_id, exception_hash, archived_at) VALUES (:project_id, :exception_hash, :archived_at) ON CONFLICT (project_id, exception_hash) DO UPDATE SET archived_at = excluded.archived_at",+ lit.P{"project_id": projectId, "exception_hash": hash, "archived_at": now})+ if err != nil {+ return err+ }+ if _, err := tx.ExecContext(ctx, query, args...); err != nil {+ return err+ }+ }++ return tx.Commit()+}++func (e *exceptionStackTraceRepository) UnarchiveByHashes(ctx context.Context, projectId uuid.UUID, hashes []string) error {+ if len(hashes) == 0 {+ return nil+ }++ params := lit.P{"project_id": projectId}+ placeholders := make([]string, len(hashes))+ for i, h := range hashes {+ key := fmt.Sprintf("hash_%d", i)+ placeholders[i] = ":" + key+ params[key] = h+ }++ query := "DELETE FROM archived_exceptions WHERE project_id = :project_id AND exception_hash IN (" + strings.Join(placeholders, ",") + ")"+ parsedQuery, args, err := lit.ParseNamedQuery(db.Driver, query, params)+ if err != nil {+ return err+ }++ _, err = db.TelemetryDB.ExecContext(ctx, parsedQuery, args...)+ return err+}++func (e *exceptionStackTraceRepository) IsArchived(ctx context.Context, projectId uuid.UUID, hash string) (bool, error) {+ result, err := lit.SelectSingleNamed[models.CountResult](db.TelemetryDB,+ "SELECT COUNT(*) AS count FROM archived_exceptions WHERE project_id = :project_id AND exception_hash = :exception_hash",+ lit.P{"project_id": projectId, "exception_hash": hash})+ if err != nil {+ return false, err+ }+ if result == nil {+ return false, nil+ }+ return result.Count > 0, nil+}++func (e *exceptionStackTraceRepository) FindExceptionByTraceId(ctx context.Context, projectId uuid.UUID, traceId uuid.UUID) (*models.ExceptionStackTrace, error) {+ row, err := lit.SelectSingleNamed[exceptionRow](db.TelemetryDB,+ `SELECT id, project_id, trace_id, trace_type, exception_hash, stack_trace, recorded_at, attributes, app_version, server_name, is_message, distributed_trace_id, session_id+ FROM exception_stack_traces WHERE project_id = :project_id AND trace_id = :trace_id AND is_message = 0 LIMIT 1`,+ lit.P{"project_id": projectId, "trace_id": traceId})+ if err != nil {+ return nil, err+ }+ if row == nil {+ return nil, nil+ }+ est := row.toModel()+ return &est, nil+}++func (e *exceptionStackTraceRepository) FindAllByTraceId(ctx context.Context, projectId uuid.UUID, traceId uuid.UUID, recordedAt *time.Time) ([]models.ExceptionStackTrace, error) {+ query := `SELECT id, project_id, trace_id, trace_type, exception_hash, stack_trace, recorded_at, attributes, app_version, server_name, is_message, distributed_trace_id, session_id+ FROM exception_stack_traces WHERE project_id = :project_id AND trace_id = :trace_id`+ params := lit.P{"project_id": projectId, "trace_id": traceId}+ if recordedAt != nil {+ from, to := shared.TraceWindowBounds(*recordedAt)+ query += ` AND recorded_at >= :from AND recorded_at <= :to`+ params["from"] = from.UTC()+ params["to"] = to.UTC()+ }+ query += ` ORDER BY recorded_at ASC`++ rows, err := lit.SelectNamed[exceptionRow](db.TelemetryDB, query, params)+ if err != nil {+ return nil, err+ }++ results := make([]models.ExceptionStackTrace, 0, len(rows))+ for _, row := range rows {+ results = append(results, row.toModel())+ }+ return results, nil+}++func (e *exceptionStackTraceRepository) FindById(ctx context.Context, projectId uuid.UUID, id uuid.UUID, recordedAt *time.Time) (*models.ExceptionStackTrace, error) {+ query := `SELECT id, project_id, trace_id, trace_type, exception_hash, stack_trace, recorded_at, attributes, app_version, server_name, is_message, distributed_trace_id, session_id+ FROM exception_stack_traces WHERE project_id = :project_id AND id = :id`+ params := lit.P{"project_id": projectId, "id": id}+ if recordedAt != nil {+ from, to := shared.TraceWindowBounds(*recordedAt)+ query += ` AND recorded_at >= :from AND recorded_at <= :to`+ params["from"] = from.UTC()+ params["to"] = to.UTC()+ }+ query += ` LIMIT 1`++ row, err := lit.SelectSingleNamed[exceptionRow](db.TelemetryDB, query, params)+ if err != nil {+ return nil, err+ }+ if row == nil {+ return nil, nil+ }+ est := row.toModel()+ return &est, nil+}++func (e *exceptionStackTraceRepository) FindByDistributedTraceId(ctx context.Context, distributedTraceId uuid.UUID, projectIds []uuid.UUID, recordedAt *time.Time) ([]models.ExceptionStackTrace, error) {+ if len(projectIds) == 0 {+ return nil, nil+ }+ params := lit.P{"trace_id": distributedTraceId}+ placeholders := make([]string, len(projectIds))+ for i, pid := range projectIds {+ key := fmt.Sprintf("pid_%d", i)+ placeholders[i] = ":" + key+ params[key] = pid+ }++ query := `SELECT id, project_id, trace_id, trace_type, exception_hash, stack_trace, recorded_at, attributes, app_version, server_name, is_message, distributed_trace_id, session_id+ FROM exception_stack_traces WHERE distributed_trace_id = :trace_id AND project_id IN (` + strings.Join(placeholders, ",") + `) AND is_message = 0`+ if recordedAt != nil {+ from, to := shared.DistributedTraceWindowBounds(*recordedAt)+ query += ` AND recorded_at >= :from AND recorded_at <= :to`+ params["from"] = from.UTC()+ params["to"] = to.UTC()+ }+ query += ` ORDER BY recorded_at ASC`++ parsedQuery, args, err := lit.ParseNamedQuery(db.Driver, query, params)+ if err != nil {+ return nil, err+ }++ sqlRows, err := db.TelemetryDB.QueryContext(ctx, parsedQuery, args...)+ if err != nil {+ return nil, err+ }+ defer sqlRows.Close()++ var results []models.ExceptionStackTrace+ for sqlRows.Next() {+ var row exceptionRow+ if err := sqlRows.Scan(&row.Id, &row.ProjectId, &row.TraceId, &row.TraceType, &row.ExceptionHash, &row.StackTrace,+ &row.RecordedAt, &row.Attributes, &row.AppVersion, &row.ServerName, &row.IsMessage, &row.DistributedTraceId, &row.SessionId); err != nil {+ return nil, err+ }+ results = append(results, row.toModel())+ }+ return results, nil+}++// FindAllBySessionId returns all exceptions/messages stamped with the given session_id, ordered by time.+func (e *exceptionStackTraceRepository) FindAllBySessionId(ctx context.Context, projectId, sessionId uuid.UUID) ([]models.ExceptionStackTrace, error) {+ rows, err := lit.SelectNamed[exceptionRow](db.TelemetryDB,+ `SELECT id, project_id, trace_id, trace_type, exception_hash, stack_trace, recorded_at, attributes, app_version, server_name, is_message, distributed_trace_id, session_id+ FROM exception_stack_traces+ WHERE project_id = :project_id AND session_id = :session_id+ ORDER BY recorded_at ASC`,+ lit.P{"project_id": projectId, "session_id": sessionId})+ if err != nil {+ return nil, err+ }+ out := make([]models.ExceptionStackTrace, 0, len(rows))+ for _, row := range rows {+ out = append(out, row.toModel())+ }+ return out, nil+}++// GetSessionIdForException returns the session_id for the given exception or nil when not linked.+func (e *exceptionStackTraceRepository) GetSessionIdForException(ctx context.Context, projectId, exceptionId uuid.UUID) (*uuid.UUID, error) {+ row, err := lit.SelectSingleNamed[exceptionRow](db.TelemetryDB,+ `SELECT id, project_id, trace_id, trace_type, exception_hash, stack_trace, recorded_at, attributes, app_version, server_name, is_message, distributed_trace_id, session_id+ FROM exception_stack_traces+ WHERE project_id = :project_id AND id = :id LIMIT 1`,+ lit.P{"project_id": projectId, "id": exceptionId})+ if err != nil || row == nil {+ return nil, err+ }+ return row.SessionId, nil+}++var ExceptionStackTraceRepository = &exceptionStackTraceRepository{}diff --git a/backend/app/repositories/telemetry/duckdb/fired_notification.repository.go b/backend/app/repositories/telemetry/duckdb/fired_notification.repository.gonew file mode 100644index 00000000..43b0740c--- /dev/null+++ b/backend/app/repositories/telemetry/duckdb/fired_notification.repository.go@@ -0,0 +1,124 @@+//go:build telemetry_duckdb++package duckdb++import (+ "context"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/shared"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/sqlitetypes"+ "strings"+ "time"++ "github.com/duckdb/duckdb-go/v2"+ "github.com/google/uuid"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"+)++type firedNotificationRepository struct{}++func (r *firedNotificationRepository) Insert(ctx context.Context, n shared.FiredNotification) error {+ var rowErr error+ err := withAppender(ctx, "fired_notifications", func(appender *duckdb.Appender) {+ // Column order matches the fired_notifications DDL: fired_at precedes url.+ rowErr = appender.AppendRow(+ n.ProjectId.String(),+ int64(n.RuleId),+ n.RuleType,+ n.RuleName,+ n.ChannelType,+ n.ChannelName,+ n.Severity,+ n.Subject,+ n.Body,+ n.Status,+ n.ErrorMsg,+ n.Endpoint,+ n.FiredAt.UTC(),+ n.URL,+ )+ })+ if rowErr != nil {+ return rowErr+ }+ return err+}++func (r *firedNotificationRepository) FindByProject(ctx context.Context, projectId uuid.UUID, page int, pageSize int, search string, from *time.Time, to *time.Time) ([]*models.NotificationHistoryEntry, int64, error) {+ where := "WHERE project_id = ?"+ args := []interface{}{projectId.String()}++ if search != "" {+ where += " AND (LOWER(rule_name) LIKE ? OR LOWER(channel_name) LIKE ? OR LOWER(subject) LIKE ?)"+ pattern := "%" + strings.ToLower(search) + "%"+ args = append(args, pattern, pattern, pattern)+ }+ if from != nil {+ where += " AND fired_at >= ?"+ args = append(args, from.UTC())+ }+ if to != nil {+ where += " AND fired_at <= ?"+ args = append(args, to.UTC())+ }++ var total int64+ if err := db.TelemetryDB.QueryRowContext(ctx, "SELECT COUNT(*) FROM fired_notifications "+where, args...).Scan(&total); err != nil {+ return nil, 0, err+ }++ query := "SELECT rule_id, rule_type, rule_name, channel_type, channel_name, severity, subject, body, status, error_message, url, fired_at FROM fired_notifications " ++ where + " ORDER BY fired_at DESC LIMIT ? OFFSET ?"+ args = append(args, pageSize, (page-1)*pageSize)++ rows, err := db.TelemetryDB.QueryContext(ctx, query, args...)+ if err != nil {+ return nil, 0, err+ }+ defer rows.Close()++ var items []*models.NotificationHistoryEntry+ for rows.Next() {+ entry := &models.NotificationHistoryEntry{}+ var firedAt sqlitetypes.SQLiteTime+ if err := rows.Scan(+ &entry.RuleId, &entry.RuleType, &entry.RuleName, &entry.ChannelType, &entry.ChannelName,+ &entry.Severity, &entry.Subject, &entry.Body, &entry.Status, &entry.ErrorMessage,+ &entry.URL, &firedAt,+ ); err != nil {+ return nil, 0, err+ }+ entry.CreatedAt = firedAt.Time+ items = append(items, entry)+ }+ if err := rows.Err(); err != nil {+ return nil, 0, err+ }++ return items, total, nil+}++func (r *firedNotificationRepository) FindLastFiredPerRule(ctx context.Context) (map[int]time.Time, error) {+ rows, err := db.TelemetryDB.QueryContext(ctx, "SELECT rule_id, MAX(fired_at) FROM fired_notifications WHERE status = 'sent' GROUP BY rule_id")+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ result := make(map[int]time.Time)+ for rows.Next() {+ var ruleId int+ var firedAt sqlitetypes.SQLiteTime+ if err := rows.Scan(&ruleId, &firedAt); err != nil {+ return nil, err+ }+ result[ruleId] = firedAt.Time+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }++ return result, nil+}++var FiredNotificationRepository = &firedNotificationRepository{}diff --git a/backend/app/repositories/telemetry/duckdb/helpers.go b/backend/app/repositories/telemetry/duckdb/helpers.gonew file mode 100644index 00000000..af14e424--- /dev/null+++ b/backend/app/repositories/telemetry/duckdb/helpers.go@@ -0,0 +1,97 @@+//go:build telemetry_duckdb++package duckdb++import (+ "context"+ "encoding/json"+ "fmt"+ "sync"+ "time"++ "github.com/duckdb/duckdb-go/v2"+ "github.com/tracewayapp/traceway/backend/app/db"+ traceway "go.tracewayapp.com"+)++// The DuckDB Appender rejects typed Go pointers for nullable columns+// (cast error: cannot cast *string to string). It accepts an untyped nil+// for SQL NULL or the dereferenced value otherwise.+func nullableString(s *string) any {+ if s == nil {+ return nil+ }+ return *s+}++const dropReportInterval = time.Minute++var (+ dropReportMu sync.Mutex+ droppedSinceReport = map[string]uint64{}+ lastDropReportAt = map[string]time.Time{}+)++func captureDroppedRow(table string, err error) {+ db.RecordTelemetryRowDropped(table)++ var report uint64+ dropReportMu.Lock()+ droppedSinceReport[table]+++ if time.Since(lastDropReportAt[table]) >= dropReportInterval {+ report = droppedSinceReport[table]+ droppedSinceReport[table] = 0+ lastDropReportAt[table] = time.Now()+ }+ dropReportMu.Unlock()++ if report > 0 {+ traceway.CaptureException(fmt.Errorf("duckdb %s insert: dropped %d rows since last report, latest: %w", table, report, err))+ }+}++func timeBucketExpr(column string, intervalSeconds int) string {+ return fmt.Sprintf("time_bucket(to_seconds(%d), %s, TIMESTAMP '1970-01-01')", intervalSeconds, column)+}++func boolToInt(b bool) int64 {+ if b {+ return 1+ }+ return 0+}++func attrJSON(m map[string]string) (string, error) {+ if len(m) == 0 {+ return "{}", nil+ }+ b, err := json.Marshal(m)+ if err != nil {+ return "", err+ }+ return string(b), nil+}++// withAppender runs fn with an Appender on a dedicated connection — the+// Appender API is not reachable through database/sql, and Close flushes+// the appended rows.+func withAppender(ctx context.Context, table string, fn func(*duckdb.Appender)) error {+ conn, err := db.DuckDBConnector.Connect(ctx)+ if err != nil {+ db.RecordTelemetryInsertFailure()+ return err+ }+ defer conn.Close()++ appender, err := duckdb.NewAppenderFromConn(conn, "", table)+ if err != nil {+ db.RecordTelemetryInsertFailure()+ return err+ }+ fn(appender)+ if err := appender.Close(); err != nil {+ db.RecordTelemetryInsertFailure()+ return err+ }+ return nil+}diff --git a/backend/app/repositories/telemetry/duckdb/log_record.repository.go b/backend/app/repositories/telemetry/duckdb/log_record.repository.gonew file mode 100644index 00000000..243a3b19--- /dev/null+++ b/backend/app/repositories/telemetry/duckdb/log_record.repository.go@@ -0,0 +1,296 @@+//go:build telemetry_duckdb++package duckdb++import (+ "context"+ "fmt"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/shared"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/sqlitetypes"+ "strings"++ "github.com/duckdb/duckdb-go/v2"+ "github.com/google/uuid"+ "github.com/tracewayapp/lit/v2"++ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"+)++type logRecord struct {+ Id uuid.UUID `lit:"id"`+ ProjectId uuid.UUID `lit:"project_id"`+ Timestamp sqlitetypes.SQLiteTime `lit:"timestamp"`+ TraceId string `lit:"trace_id"`+ SpanId string `lit:"span_id"`+ TraceFlags uint8 `lit:"trace_flags"`+ SeverityText string `lit:"severity_text"`+ SeverityNumber uint8 `lit:"severity_number"`+ ServiceName string `lit:"service_name"`+ Body string `lit:"body"`+ ResourceSchemaUrl string `lit:"resource_schema_url"`+ ResourceAttributes sqlitetypes.SQLiteJSONMap `lit:"resource_attributes"`+ ScopeSchemaUrl string `lit:"scope_schema_url"`+ ScopeName string `lit:"scope_name"`+ ScopeVersion string `lit:"scope_version"`+ ScopeAttributes sqlitetypes.SQLiteJSONMap `lit:"scope_attributes"`+ LogAttributes sqlitetypes.SQLiteJSONMap `lit:"log_attributes"`+ Total int64 `lit:"total"`+}++func init() {+ models.ExtensionModelRegistrations = append(models.ExtensionModelRegistrations, func(driver lit.Driver) {+ lit.RegisterModel[logRecord](driver)+ })+}++func (r *logRecord) toModel() models.LogRecord {+ lr := models.LogRecord{+ Id: r.Id,+ ProjectId: r.ProjectId,+ Timestamp: r.Timestamp.Time,+ TraceId: r.TraceId,+ SpanId: r.SpanId,+ TraceFlags: r.TraceFlags,+ SeverityText: r.SeverityText,+ SeverityNumber: r.SeverityNumber,+ ServiceName: r.ServiceName,+ Body: r.Body,+ ResourceSchemaUrl: r.ResourceSchemaUrl,+ ScopeSchemaUrl: r.ScopeSchemaUrl,+ ScopeName: r.ScopeName,+ ScopeVersion: r.ScopeVersion,+ }+ if r.ResourceAttributes != nil {+ lr.ResourceAttributes = map[string]string(r.ResourceAttributes)+ }+ if r.ScopeAttributes != nil {+ lr.ScopeAttributes = map[string]string(r.ScopeAttributes)+ }+ if r.LogAttributes != nil {+ lr.LogAttributes = map[string]string(r.LogAttributes)+ }+ return lr+}++type logRecordRepository struct{}++func (r *logRecordRepository) InsertAsync(ctx context.Context, records []models.LogRecord) error {+ if len(records) == 0 {+ return nil+ }++ return withAppender(ctx, "log_records", func(appender *duckdb.Appender) {++ for _, lr := range records {+ resourceJSON, err := attrJSON(lr.ResourceAttributes)+ if err != nil {+ captureDroppedRow("log_records", err)+ continue+ }+ scopeJSON, err := attrJSON(lr.ScopeAttributes)+ if err != nil {+ captureDroppedRow("log_records", err)+ continue+ }+ logJSON, err := attrJSON(lr.LogAttributes)+ if err != nil {+ captureDroppedRow("log_records", err)+ continue+ }++ if err := appender.AppendRow(+ lr.Id.String(),+ lr.ProjectId.String(),+ lr.Timestamp.UTC(),+ lr.TraceId,+ lr.SpanId,+ int64(lr.TraceFlags),+ lr.SeverityText,+ int64(lr.SeverityNumber),+ lr.ServiceName,+ lr.Body,+ lr.ResourceSchemaUrl,+ resourceJSON,+ lr.ScopeSchemaUrl,+ lr.ScopeName,+ lr.ScopeVersion,+ scopeJSON,+ logJSON,+ ); err != nil {+ captureDroppedRow("log_records", err)+ }+ }++ })+}++func (r *logRecordRepository) Search(ctx context.Context, params shared.LogSearchParams) ([]models.LogRecord, int64, error) {+ where, args := r.buildWhere(params)++ orderBy := r.resolveOrderBy(params.OrderBy)+ direction := "DESC"+ if strings.EqualFold(params.SortDirection, "asc") {+ direction = "ASC"+ }++ if params.PageSize <= 0 {+ params.PageSize = 50+ }+ if params.Page <= 0 {+ params.Page = 1+ }+ offset := (params.Page - 1) * params.PageSize++ args["limit"] = params.PageSize+ args["offset"] = offset++ // COUNT(*) OVER () counts the filtered rows before LIMIT, so one scan+ // yields both the page and the total.+ query := fmt.Sprintf(`SELECT id, project_id, timestamp, trace_id, span_id, trace_flags,+ severity_text, severity_number, service_name, body,+ resource_schema_url, resource_attributes,+ scope_schema_url, scope_name, scope_version, scope_attributes,+ log_attributes, COUNT(*) OVER () AS total+ FROM log_records+ WHERE %s+ ORDER BY %s %s+ LIMIT :limit OFFSET :offset`, where, orderBy, direction)++ rows, err := lit.SelectNamed[logRecord](db.TelemetryDB, query, args)+ if err != nil {+ return nil, 0, err+ }++ count := int64(0)+ if len(rows) > 0 {+ count = rows[0].Total+ } else if params.Page > 1 {+ // An offset past the last row returns no rows and thus no window+ // total; only then fall back to a separate count scan.+ countResult, err := lit.SelectSingleNamed[models.CountResult](db.TelemetryDB,+ "SELECT COUNT(*) AS count FROM log_records WHERE "+where, args)+ if err != nil {+ return nil, 0, err+ }+ if countResult != nil {+ count = int64(countResult.Count)+ }+ }++ records := make([]models.LogRecord, 0, len(rows))+ for _, row := range rows {+ records = append(records, row.toModel())+ }+ return records, count, nil+}++func (r *logRecordRepository) FindByTraceId(ctx context.Context, projectId uuid.UUID, traceId string) ([]models.LogRecord, error) {+ rows, err := lit.SelectNamed[logRecord](db.TelemetryDB,+ `SELECT id, project_id, timestamp, trace_id, span_id, trace_flags,+ severity_text, severity_number, service_name, body,+ resource_schema_url, resource_attributes,+ scope_schema_url, scope_name, scope_version, scope_attributes,+ log_attributes+ FROM log_records+ WHERE project_id = :project_id AND trace_id = :trace_id+ ORDER BY timestamp ASC`,+ lit.P{"project_id": projectId, "trace_id": traceId})+ if err != nil {+ return nil, err+ }++ records := make([]models.LogRecord, 0, len(rows))+ for _, row := range rows {+ records = append(records, row.toModel())+ }+ return records, nil+}++func (r *logRecordRepository) buildWhere(params shared.LogSearchParams) (string, lit.P) {+ clauses := []string{"project_id = :project_id", "timestamp >= :from", "timestamp <= :to"}+ args := lit.P{+ "project_id": params.ProjectId,+ "from": params.FromDate.UTC(),+ "to": params.ToDate.UTC(),+ }++ if params.MinSeverity > 0 {+ clauses = append(clauses, "severity_number >= :min_severity")+ args["min_severity"] = params.MinSeverity+ }+ if params.ServiceName != "" {+ clauses = append(clauses, "service_name = :service_name")+ args["service_name"] = params.ServiceName+ }+ if len(params.TraceIds) > 0 {+ placeholders := make([]string, len(params.TraceIds))+ for i, tid := range params.TraceIds {+ key := fmt.Sprintf("tid%d", i)+ placeholders[i] = ":" + key+ args[key] = tid+ }+ clauses = append(clauses, "trace_id IN ("+strings.Join(placeholders, ", ")+")")+ } else if params.TraceId != "" {+ clauses = append(clauses, "trace_id = :trace_id")+ args["trace_id"] = params.TraceId+ }++ for i, f := range params.AttributeFilters {+ col := attrColumn(f.Scope)+ if col == "" {+ continue+ }+ keyPH := fmt.Sprintf("attr_k%d", i)+ valPH := fmt.Sprintf("attr_v%d", i)+ clauses = append(clauses,+ fmt.Sprintf("json_extract_string(%s, '$.\"' || :%s || '\"') = :%s", col, keyPH, valPH))+ args[keyPH] = f.Key+ args[valPH] = f.Value+ }++ if params.Search != "" {+ switch params.SearchType {+ case "service":+ clauses = append(clauses, "INSTR(LOWER(service_name), LOWER(:search)) > 0")+ args["search"] = params.Search+ case "trace":+ if _, exists := args["trace_id"]; !exists {+ clauses = append(clauses, "trace_id = :search")+ args["search"] = params.Search+ }+ default:+ clauses = append(clauses, "INSTR(LOWER(body), LOWER(:search)) > 0")+ args["search"] = params.Search+ }+ }++ return strings.Join(clauses, " AND "), args+}++func attrColumn(scope string) string {+ switch scope {+ case "resource":+ return "resource_attributes"+ case "scope":+ return "scope_attributes"+ case "log":+ return "log_attributes"+ default:+ return ""+ }+}++func (r *logRecordRepository) resolveOrderBy(orderBy string) string {+ allowed := map[string]string{+ "timestamp": "timestamp",+ "severity_number": "severity_number",+ "service_name": "service_name",+ }+ if col, ok := allowed[orderBy]; ok {+ return col+ }+ return "timestamp"+}++var LogRecordRepository = &logRecordRepository{}diff --git a/backend/app/repositories/telemetry/duckdb/metric_point.repository.go b/backend/app/repositories/telemetry/duckdb/metric_point.repository.gonew file mode 100644index 00000000..2a3262e3--- /dev/null+++ b/backend/app/repositories/telemetry/duckdb/metric_point.repository.go@@ -0,0 +1,312 @@+//go:build telemetry_duckdb++package duckdb++import (+ "context"+ "database/sql"+ "fmt"+ "strings"+ "time"++ "github.com/duckdb/duckdb-go/v2"+ "github.com/google/uuid"+ "github.com/tracewayapp/lit/v2"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/shared"+)++type metricPointRepository struct{}++type avgResult struct {+ Value float64 `lit:"agg_value"`+}++type distinctServerResult struct {+ ServerName string `lit:"sn"`+}++type tagValueRow struct {+ TagValue string `lit:"tag_value"`+}++func init() {+ models.ExtensionModelRegistrations = append(models.ExtensionModelRegistrations, func(driver lit.Driver) {+ lit.RegisterModel[avgResult](driver)+ lit.RegisterModel[distinctServerResult](driver)+ lit.RegisterModel[tagValueRow](driver)+ })+}++func (r *metricPointRepository) InsertAsync(ctx context.Context, points []models.MetricPoint) error {+ if len(points) == 0 {+ return nil+ }++ return withAppender(ctx, "metric_points", func(appender *duckdb.Appender) {++ for _, p := range points {+ tagsJSON, err := attrJSON(p.Tags)+ if err != nil {+ captureDroppedRow("metric_points", err)+ continue+ }+ if err := appender.AppendRow(p.ProjectId.String(), p.Name, p.Value, tagsJSON, p.RecordedAt.UTC(), p.Tags["server_name"]); err != nil {+ captureDroppedRow("metric_points", err)+ }+ }++ })+}++func (r *metricPointRepository) QueryTimeSeries(ctx context.Context, projectId uuid.UUID, name string, from, to time.Time, intervalMinutes int, aggregation string, tagFilters map[string]string, groupBy string) (map[string][]models.TimeSeriesPoint, error) {+ secs := intervalMinutes * 60+ aggFunc := duckdbAggregationFunc(aggregation)+ hasGroupBy := groupBy != ""++ selectClause := "SELECT " + timeBucketExpr("recorded_at", secs) + " AS bucket"+ if hasGroupBy {+ selectClause += ", json_extract_string(tags, '$.\"' || :group_by || '\"') AS group_key"+ }+ selectClause += ", " + aggFunc + " AS agg_value FROM metric_points WHERE project_id = :project_id AND name = :name AND recorded_at >= :from AND recorded_at <= :to"++ params := lit.P{+ "project_id": projectId,+ "name": name,+ "from": from.UTC(),+ "to": to.UTC(),+ }+ if hasGroupBy {+ params["group_by"] = groupBy+ }++ filterClauses := ""+ for i, k := range shared.SortedKeys(tagFilters) {+ fk := fmt.Sprintf("fk_%d", i)+ fv := fmt.Sprintf("fv_%d", i)+ filterClauses += fmt.Sprintf(" AND json_extract_string(tags, '$.\"' || :%s || '\"') = :%s", fk, fv)+ params[fk] = k+ params[fv] = tagFilters[k]+ }++ query := selectClause + filterClauses + " GROUP BY bucket"+ if hasGroupBy {+ query += ", group_key"+ }+ query += " ORDER BY bucket ASC"++ parsedQuery, args, err := lit.ParseNamedQuery(db.Driver, query, params)+ if err != nil {+ return nil, err+ }++ rows, err := db.TelemetryDB.QueryContext(ctx, parsedQuery, args...)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ result := make(map[string][]models.TimeSeriesPoint)+ for rows.Next() {+ var bucket time.Time+ var value float64+ groupKey := "__all__"++ if hasGroupBy {+ var groupKeyNullable *string+ if err := rows.Scan(&bucket, &groupKeyNullable, &value); err != nil {+ return nil, err+ }+ if groupKeyNullable != nil {+ groupKey = *groupKeyNullable+ }+ } else {+ if err := rows.Scan(&bucket, &value); err != nil {+ return nil, err+ }+ }++ if groupKey == "" {+ groupKey = "(empty)"+ }+ result[groupKey] = append(result[groupKey], models.TimeSeriesPoint{+ Timestamp: bucket,+ Value: value,+ })+ }+ return result, nil+}++func (r *metricPointRepository) DiscoverMetrics(ctx context.Context, projectId uuid.UUID, from, to time.Time) ([]models.DiscoveredMetric, error) {+ query, args, err := lit.ParseNamedQuery(db.Driver,+ `SELECT name, COALESCE(t.k, '') AS tag_key+ FROM metric_points+ LEFT JOIN LATERAL unnest(json_keys(tags)) AS t(k) ON true+ WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to+ GROUP BY name, t.k+ ORDER BY name ASC, t.k ASC`,+ lit.P{"project_id": projectId, "from": from.UTC(), "to": to.UTC()})+ if err != nil {+ return nil, err+ }++ rows, err := db.TelemetryDB.QueryContext(ctx, query, args...)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ byName := make(map[string]*models.DiscoveredMetric)+ order := make([]string, 0)+ for rows.Next() {+ var name string+ var tagKey sql.NullString+ if err := rows.Scan(&name, &tagKey); err != nil {+ return nil, err+ }+ m, ok := byName[name]+ if !ok {+ m = &models.DiscoveredMetric{Name: name, TagKeys: []string{}}+ byName[name] = m+ order = append(order, name)+ }+ if tagKey.Valid && tagKey.String != "" {+ m.TagKeys = append(m.TagKeys, tagKey.String)+ }+ }++ metrics := make([]models.DiscoveredMetric, 0, len(order))+ for _, n := range order {+ metrics = append(metrics, *byName[n])+ }+ return metrics, nil+}++func (r *metricPointRepository) DiscoverTagValues(ctx context.Context, projectId uuid.UUID, metricName, tagKey string, from, to time.Time) ([]string, error) {+ results, err := lit.SelectNamed[tagValueRow](db.TelemetryDB,+ `SELECT DISTINCT json_extract_string(tags, '$."' || :tag_key || '"') AS tag_value+ FROM metric_points+ WHERE project_id = :project_id AND name = :name AND recorded_at >= :from AND recorded_at <= :to+ AND json_extract_string(tags, '$."' || :tag_key || '"') IS NOT NULL+ AND json_extract_string(tags, '$."' || :tag_key || '"') != ''+ ORDER BY tag_value ASC`,+ lit.P{"project_id": projectId, "name": metricName, "tag_key": tagKey, "from": from.UTC(), "to": to.UTC()})+ if err != nil {+ return nil, err+ }++ values := make([]string, 0, len(results))+ for _, r := range results {+ values = append(values, r.TagValue)+ }+ return values, nil+}++func (r *metricPointRepository) GetAverageBetween(ctx context.Context, projectId uuid.UUID, name string, start, end time.Time) (float64, error) {+ result, err := lit.SelectSingleNamed[avgResult](db.TelemetryDB,+ "SELECT COALESCE(avg(value), 0) AS agg_value FROM metric_points WHERE project_id = :project_id AND name = :name AND recorded_at >= :from AND recorded_at <= :to",+ lit.P{"project_id": projectId, "name": name, "from": start.UTC(), "to": end.UTC()})+ if err != nil {+ return 0, err+ }+ if result == nil {+ return 0, nil+ }+ return result.Value, nil+}++func (r *metricPointRepository) GetDistinctServers(ctx context.Context, projectId uuid.UUID, start, end time.Time) ([]string, error) {+ results, err := lit.SelectNamed[distinctServerResult](db.TelemetryDB,+ `SELECT DISTINCT server_name AS sn+ FROM metric_points+ WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to+ AND server_name != ''+ ORDER BY sn ASC`,+ lit.P{"project_id": projectId, "from": start.UTC(), "to": end.UTC()})+ if err != nil {+ return nil, err+ }++ servers := make([]string, 0, len(results))+ for _, r := range results {+ servers = append(servers, r.ServerName)+ }+ return servers, nil+}++func (r *metricPointRepository) GetAverageByIntervalPerServer(ctx context.Context, projectId uuid.UUID, name string, start, end time.Time, intervalMinutes int, servers []string) (map[string][]models.TimeSeriesPoint, error) {+ secs := intervalMinutes * 60++ params := lit.P{+ "project_id": projectId,+ "name": name,+ "from": start.UTC(),+ "to": end.UTC(),+ }++ query := fmt.Sprintf(`SELECT+ %s AS bucket,+ server_name AS sn,+ avg(value) AS avg_value+ FROM metric_points+ WHERE project_id = :project_id AND name = :name AND recorded_at >= :from AND recorded_at <= :to`, timeBucketExpr("recorded_at", secs))++ if len(servers) > 0 {+ placeholders := make([]string, len(servers))+ for i, s := range servers {+ key := fmt.Sprintf("srv_%d", i)+ placeholders[i] = ":" + key+ params[key] = s+ }+ query += " AND server_name IN (" + strings.Join(placeholders, ", ") + ")"+ } else {+ query += " AND server_name != ''"+ }++ query += " GROUP BY bucket, sn ORDER BY bucket ASC, sn ASC"++ parsedQuery, args, err := lit.ParseNamedQuery(db.Driver, query, params)+ if err != nil {+ return nil, err+ }++ rows, err := db.TelemetryDB.QueryContext(ctx, parsedQuery, args...)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ result := make(map[string][]models.TimeSeriesPoint)+ for rows.Next() {+ var bucket time.Time+ var serverName string+ var value float64+ if err := rows.Scan(&bucket, &serverName, &value); err != nil {+ return nil, err+ }++ result[serverName] = append(result[serverName], models.TimeSeriesPoint{+ Timestamp: bucket,+ Value: value,+ })+ }+ return result, nil+}++func duckdbAggregationFunc(agg string) string {+ switch agg {+ case "min":+ return "min(value)"+ case "max":+ return "max(value)"+ case "sum":+ return "sum(value)"+ case "count":+ return "CAST(COUNT(*) AS DOUBLE)"+ default:+ return "avg(value)"+ }+}++var MetricPointRepository = &metricPointRepository{}diff --git a/backend/app/repositories/telemetry/duckdb/profile.repository.go b/backend/app/repositories/telemetry/duckdb/profile.repository.gonew file mode 100644index 00000000..febefeb8--- /dev/null+++ b/backend/app/repositories/telemetry/duckdb/profile.repository.go@@ -0,0 +1,629 @@+//go:build telemetry_duckdb++package duckdb++import (+ "context"+ "database/sql"+ "encoding/json"+ "fmt"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/shared"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/sqlitetypes"+ "sort"+ "time"++ "github.com/duckdb/duckdb-go/v2"+ "github.com/google/uuid"+ "github.com/tracewayapp/lit/v2"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"+ "github.com/tracewayapp/traceway/backend/app/profiling"+)++type profileGroupRow struct {+ ServiceName string `lit:"service_name"`+ ProfileType string `lit:"profile_type"`+ Unit string `lit:"unit"`+ IsGauge int64 `lit:"is_gauge"`+ ProfileCount int64 `lit:"profile_count"`+ SampleCount int64 `lit:"sample_count"`+ TotalValue int64 `lit:"total_value"`+ LastSeen sqlitetypes.SQLiteTime `lit:"last_seen"`+}++type labelValueRow struct {+ Value string `lit:"v"`+}++type profileTypeRow struct {+ Type string `lit:"type"`+ Unit string `lit:"unit"`+ IsGauge int64 `lit:"is_gauge"`+}++type profileDimValueRow struct {+ Key *string `lit:"k"`+ Total float64 `lit:"tv"`+}++func init() {+ models.ExtensionModelRegistrations = append(models.ExtensionModelRegistrations, func(driver lit.Driver) {+ lit.RegisterModel[profileGroupRow](driver)+ lit.RegisterModel[labelValueRow](driver)+ lit.RegisterModel[profileTypeRow](driver)+ lit.RegisterModel[profileDimValueRow](driver)+ })+}++type profileRepository struct{}++func (r *profileRepository) InsertStacksAsync(ctx context.Context, stacks []models.ProfileStack) error {+ if len(stacks) == 0 {+ return nil+ }++ tx, err := db.TelemetryDB.BeginTx(ctx, nil)+ if err != nil {+ return err+ }+ defer tx.Rollback()++ for _, s := range stacks {+ stackJSON := "[]"+ if len(s.Stack) > 0 {+ b, err := json.Marshal(s.Stack)+ if err != nil {+ return err+ }+ stackJSON = string(b)+ }+ query, args, err := lit.ParseNamedQuery(db.Driver,+ "INSERT INTO profiling_stacks (project_id, service_name, stack_hash, stack, last_seen) VALUES (:project_id, :service_name, :stack_hash, :stack, :last_seen) ON CONFLICT (project_id, service_name, stack_hash) DO UPDATE SET last_seen = excluded.last_seen",+ lit.P{+ "project_id": s.ProjectId.String(),+ "service_name": s.ServiceName,+ "stack_hash": int64(s.StackHash),+ "stack": stackJSON,+ "last_seen": s.LastSeen.UTC(),+ })+ if err != nil {+ return err+ }+ if _, err := tx.ExecContext(ctx, query, args...); err != nil {+ return err+ }+ }+ return tx.Commit()+}++func (r *profileRepository) InsertSamplesAsync(ctx context.Context, samples []models.ProfileSample) error {+ if len(samples) == 0 {+ return nil+ }++ return withAppender(ctx, "profiling_samples", func(appender *duckdb.Appender) {++ for _, s := range samples {+ labelsJSON, err := attrJSON(s.Labels)+ if err != nil {+ captureDroppedRow("profiling_samples", err)+ continue+ }+ if err := appender.AppendRow(+ s.ProjectId.String(),+ s.ProfileId.String(),+ s.ServiceName,+ s.Type,+ s.Start.UTC(),+ s.End.UTC(),+ int64(s.StackHash),+ s.Value,+ labelsJSON,+ s.ServerName,+ s.AppVersion,+ s.TraceId,+ s.SpanId,+ s.Unit,+ boolToInt(s.IsGauge),+ ); err != nil {+ captureDroppedRow("profiling_samples", err)+ }+ }++ })+}++func (r *profileRepository) InsertProfilesAsync(ctx context.Context, profiles []models.Profile) error {+ if len(profiles) == 0 {+ return nil+ }++ return withAppender(ctx, "profiles", func(appender *duckdb.Appender) {++ for _, p := range profiles {+ attributesJSON, err := attrJSON(p.Attributes)+ if err != nil {+ captureDroppedRow("profiles", err)+ continue+ }++ var distributedTraceId *string+ if p.DistributedTraceId != nil {+ v := p.DistributedTraceId.String()+ distributedTraceId = &v+ }++ if err := appender.AppendRow(+ p.Id.String(),+ p.ProjectId.String(),+ p.RecordedAt.UTC(),+ int64(p.Duration),+ p.ServiceName,+ p.ProfileType,+ int64(p.SampleCount),+ p.TotalValue,+ p.ServerName,+ p.AppVersion,+ attributesJSON,+ p.StorageKey,+ p.TraceId,+ p.SpanId,+ nullableString(distributedTraceId),+ p.Unit,+ boolToInt(p.IsGauge),+ ); err != nil {+ captureDroppedRow("profiles", err)+ }+ }++ })+}++func (r *profileRepository) FindGroupedByService(ctx context.Context, projectId uuid.UUID, from, to time.Time, page, pageSize int, orderBy, sortDirection, search string) ([]models.ProfileGroup, int64, error) {+ searchClause := ""+ countParams := lit.P{"project_id": projectId, "from": from.UTC(), "to": to.UTC()}+ if search != "" {+ searchClause = " AND instr(lower(service_name), lower(:search)) > 0"+ countParams["search"] = search+ }++ countResult, err := lit.SelectSingleNamed[models.CountResult](db.TelemetryDB,+ `SELECT COUNT(*) AS count FROM (+ SELECT 1 FROM profiles+ WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to`+searchClause+`+ GROUP BY service_name, profile_type) AS sub`, countParams)+ if err != nil {+ return nil, 0, err+ }+ total := int64(0)+ if countResult != nil {+ total = int64(countResult.Count)+ }++ orderByMap := map[string]string{+ "total_value": "total_value",+ "sample_count": "sample_count",+ "profile_count": "profile_count",+ "last_seen": "last_seen",+ }+ orderExpr, ok := orderByMap[orderBy]+ if !ok {+ orderExpr = "total_value"+ }+ sortDir := "DESC"+ if sortDirection == "asc" {+ sortDir = "ASC"+ }++ offset := (page - 1) * pageSize+ pageParams := lit.P{"project_id": projectId, "from": from.UTC(), "to": to.UTC(), "limit": pageSize, "offset": offset}+ if search != "" {+ pageParams["search"] = search+ }+ rows, err := lit.SelectNamed[profileGroupRow](db.TelemetryDB,+ fmt.Sprintf(`SELECT service_name, profile_type,+ MAX(unit) AS unit,+ MAX(is_gauge) AS is_gauge,+ COUNT(*) AS profile_count,+ SUM(sample_count) AS sample_count,+ SUM(total_value) AS total_value,+ MAX(recorded_at) AS last_seen+ FROM profiles+ WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to`+searchClause+`+ GROUP BY service_name, profile_type+ ORDER BY %s %s+ LIMIT :limit OFFSET :offset`, orderExpr, sortDir),+ pageParams)+ if err != nil {+ return nil, 0, err+ }++ groups := make([]models.ProfileGroup, 0, len(rows))+ for _, row := range rows {+ groups = append(groups, models.ProfileGroup{+ ServiceName: row.ServiceName,+ Type: row.ProfileType,+ Unit: row.Unit,+ IsGauge: row.IsGauge != 0,+ ProfileCount: row.ProfileCount,+ SampleCount: row.SampleCount,+ TotalValue: row.TotalValue,+ LastSeen: row.LastSeen.Time,+ })+ }++ if err := r.fillSparklines(ctx, projectId, from, to, groups); err != nil {+ return nil, 0, err+ }+ return groups, total, nil+}++func (r *profileRepository) fillSparklines(ctx context.Context, projectId uuid.UUID, from, to time.Time, groups []models.ProfileGroup) error {+ if len(groups) == 0 {+ return nil+ }+ const buckets = 16+ bucketSecs := int(to.Sub(from).Seconds()) / buckets+ if bucketSecs < 1 {+ bucketSecs = 1+ }+ alignedFrom := (from.Unix() / int64(bucketSecs)) * int64(bucketSecs)++ query, args, err := lit.ParseNamedQuery(db.Driver,+ fmt.Sprintf(`SELECT service_name, profile_type,+ (CAST(epoch(recorded_at) AS BIGINT) // %d) * %d AS bucket,+ CAST(SUM(total_value) AS DOUBLE) AS v+ FROM profiles+ WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to+ GROUP BY service_name, profile_type, bucket`, bucketSecs, bucketSecs),+ lit.P{"project_id": projectId, "from": from.UTC(), "to": to.UTC()})+ if err != nil {+ return err+ }+ sqlRows, err := db.TelemetryDB.QueryContext(ctx, query, args...)+ if err != nil {+ return err+ }+ defer sqlRows.Close()++ acc := map[string][]float64{}+ for sqlRows.Next() {+ var service, ptype string+ var bucketEpoch int64+ var v float64+ if err := sqlRows.Scan(&service, &ptype, &bucketEpoch, &v); err != nil {+ return err+ }+ idx := int((bucketEpoch - alignedFrom) / int64(bucketSecs))+ if idx < 0 {+ idx = 0+ }+ if idx >= buckets {+ idx = buckets - 1+ }+ key := service + "\x00" + ptype+ arr, ok := acc[key]+ if !ok {+ arr = make([]float64, buckets)+ acc[key] = arr+ }+ arr[idx] += v+ }+ if err := sqlRows.Err(); err != nil {+ return err+ }++ for i := range groups {+ if arr, ok := acc[groups[i].ServiceName+"\x00"+groups[i].Type]; ok {+ groups[i].Sparkline = arr+ } else {+ groups[i].Sparkline = []float64{}+ }+ }+ return nil+}++func (r *profileRepository) DiscoverTypes(ctx context.Context, projectId uuid.UUID, service string, from, to time.Time) ([]models.ProfileTypeInfo, error) {+ rows, err := lit.SelectNamed[profileTypeRow](db.TelemetryDB,+ `SELECT type, MAX(unit) AS unit, MAX(is_gauge) AS is_gauge+ FROM profiling_samples+ WHERE project_id = :project_id AND service_name = :service+ AND start_time >= :from AND start_time <= :to+ GROUP BY type+ ORDER BY type ASC`,+ lit.P{"project_id": projectId, "service": service, "from": from.UTC(), "to": to.UTC()})+ if err != nil {+ return nil, err+ }++ out := make([]models.ProfileTypeInfo, 0, len(rows))+ for _, row := range rows {+ out = append(out, models.ProfileTypeInfo{Type: row.Type, Unit: row.Unit, IsGauge: row.IsGauge != 0})+ }+ return out, nil+}++func (r *profileRepository) GetSeries(ctx context.Context, projectId uuid.UUID, service, profileType string, from, to time.Time, intervalMinutes int, isGauge bool, labelFilters map[string]string, appVersion, serverName string, normalize bool) ([]models.TimeSeriesPoint, error) {+ if intervalMinutes < 1 {+ intervalMinutes = 1+ }+ secs := intervalMinutes * 60+ agg := "SUM"+ if isGauge {+ agg = "AVG"+ }++ params := lit.P{"project_id": projectId, "type": profileType, "service": service, "from": from.UTC(), "to": to.UTC()}+ filter := duckdbLabelFilter("", labelFilters, params)+ cohort := duckdbCohortFilter("", appVersion, serverName, params)++ query, args, err := lit.ParseNamedQuery(db.Driver,+ fmt.Sprintf(`SELECT %s AS bucket,+ CAST(%s(value) AS DOUBLE) AS agg_value+ FROM profiling_samples+ WHERE project_id = :project_id AND type = :type AND service_name = :service+ AND start_time >= :from AND start_time <= :to`+filter+cohort+`+ GROUP BY bucket ORDER BY bucket ASC`, timeBucketExpr("start_time", secs), agg),+ params)+ if err != nil {+ return nil, err+ }+ sqlRows, err := db.TelemetryDB.QueryContext(ctx, query, args...)+ if err != nil {+ return nil, err+ }+ points, err := scanProfileSeriesPoints(sqlRows)+ if err != nil {+ return nil, err+ }+ shared.NormalizeSeriesPoints(points, normalize, isGauge, intervalMinutes)+ return points, nil+}++func (r *profileRepository) GetFlameGraph(ctx context.Context, projectId uuid.UUID, service, profileType string, from, to time.Time, labelFilters map[string]string, isGauge bool, appVersion, serverName string) ([]models.ProfileStackValue, error) {+ params := lit.P{"project_id": projectId, "type": profileType, "service": service, "from": from.UTC(), "to": to.UTC()}+ bareFilter := duckdbLabelFilter("", labelFilters, params)+ aliasFilter := duckdbLabelFilter("s.", labelFilters, params)+ bareCohort := duckdbCohortFilter("", appVersion, serverName, params)+ aliasCohort := duckdbCohortFilter("s.", appVersion, serverName, params)++ var query string+ if isGauge {+ // arg_max picks the profile_id of the latest sample per server (one even on ties),+ // matching SQLite's bare-column MIN/MAX semantics under DuckDB's strict GROUP BY.+ query = `WITH latest AS (+ SELECT arg_max(profile_id, start_time) AS pid+ FROM profiling_samples+ WHERE project_id = :project_id AND type = :type AND service_name = :service+ AND start_time >= :from AND start_time <= :to` + bareFilter + bareCohort + `+ GROUP BY server_name)+ SELECT st.stack AS stack_json, CAST(SUM(s.value) AS BIGINT) AS v+ FROM profiling_samples s+ JOIN latest l ON l.pid = s.profile_id+ JOIN profiling_stacks st ON st.project_id = s.project_id AND st.service_name = s.service_name AND st.stack_hash = s.stack_hash+ WHERE s.project_id = :project_id AND s.type = :type AND s.service_name = :service+ AND s.start_time >= :from AND s.start_time <= :to` + aliasFilter + aliasCohort + `+ GROUP BY s.stack_hash, st.stack+ ORDER BY v DESC LIMIT 50000`+ } else {+ query = `SELECT st.stack AS stack_json, CAST(SUM(s.value) AS BIGINT) AS v+ FROM profiling_samples s+ JOIN profiling_stacks st ON st.project_id = s.project_id AND st.service_name = s.service_name AND st.stack_hash = s.stack_hash+ WHERE s.project_id = :project_id AND s.type = :type AND s.service_name = :service+ AND s.start_time >= :from AND s.start_time <= :to` + aliasFilter + aliasCohort + `+ GROUP BY s.stack_hash, st.stack+ ORDER BY v DESC LIMIT 50000`+ }++ parsed, args, err := lit.ParseNamedQuery(db.Driver, query, params)+ if err != nil {+ return nil, err+ }+ sqlRows, err := db.TelemetryDB.QueryContext(ctx, parsed, args...)+ if err != nil {+ return nil, err+ }+ defer sqlRows.Close()++ var out []models.ProfileStackValue+ for sqlRows.Next() {+ var stackJSON string+ var value int64+ if err := sqlRows.Scan(&stackJSON, &value); err != nil {+ return nil, err+ }+ var frames []string+ if err := json.Unmarshal([]byte(stackJSON), &frames); err != nil {+ return nil, err+ }+ out = append(out, models.ProfileStackValue{Stack: frames, Value: value})+ }+ return out, sqlRows.Err()+}++func (r *profileRepository) distinctLabelValues(ctx context.Context, projectId uuid.UUID, service, profileType, key string, from, to time.Time) ([]string, error) {+ results, err := lit.SelectNamed[labelValueRow](db.TelemetryDB,+ fmt.Sprintf(`SELECT DISTINCT json_extract_string(labels, '$."' || :key || '"') AS v+ FROM profiling_samples+ WHERE project_id = :project_id AND type = :type AND service_name = :service+ AND start_time >= :from AND start_time <= :to+ AND json_extract_string(labels, '$."' || :key || '"') IS NOT NULL+ AND json_extract_string(labels, '$."' || :key || '"') != ''+ ORDER BY v ASC+ LIMIT %d`, profiling.MaxLabelValuesPerKey),+ lit.P{"project_id": projectId, "type": profileType, "service": service, "key": key, "from": from.UTC(), "to": to.UTC()})+ if err != nil {+ return nil, err+ }++ values := make([]string, 0, len(results))+ for _, row := range results {+ values = append(values, row.Value)+ }+ return values, nil+}++func (r *profileRepository) GetSeriesBreakdown(ctx context.Context, projectId uuid.UUID, service, profileType string, from, to time.Time, intervalMinutes int, isGauge bool, labelFilters map[string]string, appVersion, serverName string, normalize bool, dimension string, limit int) ([]models.ProfileSeriesGroup, error) {+ if intervalMinutes < 1 {+ intervalMinutes = 1+ }+ secs := intervalMinutes * 60+ limit = shared.ClampBreakdownLimit(limit)+ agg := "SUM"+ if isGauge {+ agg = "AVG"+ }++ params := lit.P{"project_id": projectId, "type": profileType, "service": service, "from": from.UTC(), "to": to.UTC(), "limit": limit}+ filter := duckdbLabelFilter("", labelFilters, params)+ cohort := duckdbCohortFilter("", appVersion, serverName, params)+ dimExpr, ok := duckdbDimExpr(dimension, params)+ if !ok {+ return nil, fmt.Errorf("unsupported breakdown dimension: %s", dimension)+ }++ topRows, err := lit.SelectNamed[profileDimValueRow](db.TelemetryDB,+ fmt.Sprintf(`SELECT %s AS k, CAST(%s(value) AS DOUBLE) AS tv+ FROM profiling_samples+ WHERE project_id = :project_id AND type = :type AND service_name = :service+ AND start_time >= :from AND start_time <= :to`+filter+cohort+`+ AND %s != ''+ GROUP BY k ORDER BY tv DESC LIMIT :limit`, dimExpr, agg, dimExpr),+ params)+ if err != nil {+ return nil, err+ }++ seriesQuery := fmt.Sprintf(`SELECT %s AS bucket,+ CAST(%s(value) AS DOUBLE) AS agg_value+ FROM profiling_samples+ WHERE project_id = :project_id AND type = :type AND service_name = :service+ AND start_time >= :from AND start_time <= :to`+filter+cohort+`+ AND %s = :dimval+ GROUP BY bucket ORDER BY bucket ASC`, timeBucketExpr("start_time", secs), agg, dimExpr)++ groups := make([]models.ProfileSeriesGroup, 0, len(topRows))+ for _, row := range topRows {+ if row.Key == nil {+ continue+ }+ key := *row.Key+ params["dimval"] = key+ parsed, args, err := lit.ParseNamedQuery(db.Driver, seriesQuery, params)+ if err != nil {+ return nil, err+ }+ sqlRows, err := db.TelemetryDB.QueryContext(ctx, parsed, args...)+ if err != nil {+ return nil, err+ }+ points, err := scanProfileSeriesPoints(sqlRows)+ if err != nil {+ return nil, err+ }+ shared.NormalizeSeriesPoints(points, normalize, isGauge, intervalMinutes)+ groups = append(groups, models.ProfileSeriesGroup{Key: key, Points: points})+ }+ return groups, nil+}++func (r *profileRepository) DiscoverDimensions(ctx context.Context, projectId uuid.UUID, service, profileType string, from, to time.Time) ([]string, []string, error) {+ appVersions, err := r.distinctDimensionValues(ctx, projectId, service, profileType, "app_version", from, to)+ if err != nil {+ return nil, nil, err+ }+ serverNames, err := r.distinctDimensionValues(ctx, projectId, service, profileType, "server_name", from, to)+ if err != nil {+ return nil, nil, err+ }+ return appVersions, serverNames, nil+}++func (r *profileRepository) distinctDimensionValues(ctx context.Context, projectId uuid.UUID, service, profileType, column string, from, to time.Time) ([]string, error) {+ rows, err := lit.SelectNamed[labelValueRow](db.TelemetryDB,+ fmt.Sprintf(`SELECT DISTINCT %s AS v+ FROM profiling_samples+ WHERE project_id = :project_id AND service_name = :service AND type = :type+ AND start_time >= :from AND start_time <= :to AND %s != ''+ ORDER BY %s ASC LIMIT 100`, column, column, column),+ lit.P{"project_id": projectId, "service": service, "type": profileType, "from": from.UTC(), "to": to.UTC()})+ if err != nil {+ return nil, err+ }+ values := make([]string, 0, len(rows))+ for _, row := range rows {+ values = append(values, row.Value)+ }+ return values, nil+}++func scanProfileSeriesPoints(rows *sql.Rows) ([]models.TimeSeriesPoint, error) {+ defer rows.Close()+ points := make([]models.TimeSeriesPoint, 0)+ for rows.Next() {+ var bucket time.Time+ var value float64+ if err := rows.Scan(&bucket, &value); err != nil {+ return nil, err+ }+ points = append(points, models.TimeSeriesPoint{Timestamp: bucket, Value: value})+ }+ return points, rows.Err()+}++func duckdbCohortFilter(qualifier, appVersion, serverName string, params lit.P) string {+ clause := ""+ if appVersion != "" {+ clause += fmt.Sprintf(" AND %sapp_version = :app_version", qualifier)+ params["app_version"] = appVersion+ }+ if serverName != "" {+ clause += fmt.Sprintf(" AND %sserver_name = :server_name", qualifier)+ params["server_name"] = serverName+ }+ return clause+}++func duckdbDimExpr(dimension string, params lit.P) (string, bool) {+ switch dimension {+ case "app_version":+ return "app_version", true+ case "server_name":+ return "server_name", true+ }+ key, ok := shared.BreakdownLabelKey(dimension)+ if !ok || key == "" {+ return "", false+ }+ params["dimpath"] = "$.\"" + key + "\""+ return "json_extract_string(labels, :dimpath)", true+}++func duckdbLabelFilter(qualifier string, filters map[string]string, params lit.P) string {+ if len(filters) == 0 {+ return ""+ }+ keys := make([]string, 0, len(filters))+ for k := range filters {+ keys = append(keys, k)+ }+ sort.Strings(keys)++ clause := ""+ for i, k := range keys {+ pathKey := fmt.Sprintf("lblpath_%d", i)+ valKey := fmt.Sprintf("lblval_%d", i)+ clause += fmt.Sprintf(" AND json_extract_string(%slabels, :%s) = :%s", qualifier, pathKey, valKey)+ params[pathKey] = "$.\"" + k + "\""+ params[valKey] = filters[k]+ }+ return clause+}++var ProfileRepository = &profileRepository{}++func (r *profileRepository) DiscoverLabels(ctx context.Context, projectId uuid.UUID, service, profileType string, from, to time.Time, allowKeys []string) (map[string][]string, error) {+ return shared.DiscoverLabels(ctx, allowKeys, func(ctx context.Context, key string) ([]string, error) {+ return r.distinctLabelValues(ctx, projectId, service, profileType, key, from, to)+ })+}diff --git a/backend/app/repositories/telemetry/duckdb/session.repository.go b/backend/app/repositories/telemetry/duckdb/session.repository.gonew file mode 100644index 00000000..07c9c4d2--- /dev/null+++ b/backend/app/repositories/telemetry/duckdb/session.repository.go@@ -0,0 +1,255 @@+//go:build telemetry_duckdb++package duckdb++import (+ "context"+ "encoding/json"+ "fmt"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/shared"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/sqlitetypes"+ "strings"+ "time"++ "github.com/google/uuid"+ "github.com/tracewayapp/lit/v2"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"+)++type sessionRow struct {+ Id uuid.UUID `lit:"id"`+ ProjectId uuid.UUID `lit:"project_id"`+ StartedAt sqlitetypes.SQLiteTime `lit:"started_at"`+ EndedAt *sqlitetypes.SQLiteTime `lit:"ended_at"`+ Duration int64 `lit:"duration"`+ ClientIP string `lit:"client_ip"`+ Attributes sqlitetypes.SQLiteJSONMap `lit:"attributes"`+ AppVersion string `lit:"app_version"`+ ServerName string `lit:"server_name"`+ DistributedTraceId *uuid.UUID `lit:"distributed_trace_id"`+}++type sessionRowNaming struct{ lit.DefaultDbNamingStrategy }++func (sessionRowNaming) GetTableNameFromStructName(string) string {+ return "sessions"+}++func init() {+ models.ExtensionModelRegistrations = append(models.ExtensionModelRegistrations, func(driver lit.Driver) {+ lit.RegisterModelWithNaming[sessionRow](driver, sessionRowNaming{})+ })+}++func (row *sessionRow) toModel() models.Session {+ s := models.Session{+ Id: row.Id,+ ProjectId: row.ProjectId,+ StartedAt: row.StartedAt.Time,+ Duration: row.Duration,+ ClientIP: row.ClientIP,+ AppVersion: row.AppVersion,+ ServerName: row.ServerName,+ DistributedTraceId: row.DistributedTraceId,+ }+ if row.EndedAt != nil {+ t := row.EndedAt.Time+ s.EndedAt = &t+ }+ if row.Attributes != nil {+ s.Attributes = map[string]string(row.Attributes)+ }+ return s+}++type sessionRepository struct{}++// Upsert uses DuckDB ON CONFLICT rather than the Appender because sessions carry a+// PRIMARY KEY and existing rows are mutated (ended_at/duration) as more telemetry+// arrives — the Appender is insert-only and cannot express the conflict update.+func (r *sessionRepository) Upsert(ctx context.Context, sessions []models.Session) error {+ if len(sessions) == 0 {+ return nil+ }+ const stmt = `INSERT INTO sessions+ (id, project_id, started_at, ended_at, duration, client_ip, attributes, app_version, server_name, distributed_trace_id)+ VALUES (:id, :project_id, :started_at, :ended_at, :duration, :client_ip, :attributes, :app_version, :server_name, :distributed_trace_id)+ ON CONFLICT (id) DO UPDATE SET+ ended_at = COALESCE(excluded.ended_at, sessions.ended_at),+ duration = CASE WHEN excluded.duration > 0 THEN excluded.duration ELSE sessions.duration END,+ attributes = excluded.attributes,+ app_version = excluded.app_version,+ server_name = excluded.server_name,+ distributed_trace_id = excluded.distributed_trace_id`++ tx, err := db.TelemetryDB.BeginTx(ctx, nil)+ if err != nil {+ return err+ }+ defer tx.Rollback()++ for _, s := range sessions {+ attrs := "{}"+ if len(s.Attributes) > 0 {+ b, err := json.Marshal(s.Attributes)+ if err != nil {+ return err+ }+ attrs = string(b)+ }+ var endedAt *time.Time+ if s.EndedAt != nil {+ t := s.EndedAt.UTC()+ endedAt = &t+ }+ var distTraceId *string+ if s.DistributedTraceId != nil {+ v := s.DistributedTraceId.String()+ distTraceId = &v+ }+ query, args, err := lit.ParseNamedQuery(db.Driver, stmt, lit.P{+ "id": s.Id.String(),+ "project_id": s.ProjectId.String(),+ "started_at": s.StartedAt.UTC(),+ "ended_at": endedAt,+ "duration": s.Duration,+ "client_ip": s.ClientIP,+ "attributes": attrs,+ "app_version": s.AppVersion,+ "server_name": s.ServerName,+ "distributed_trace_id": distTraceId,+ })+ if err != nil {+ return err+ }+ if _, err := tx.ExecContext(ctx, query, args...); err != nil {+ return err+ }+ }+ return tx.Commit()+}++func (r *sessionRepository) CountBetween(ctx context.Context, projectId uuid.UUID, start, end time.Time) (int64, error) {+ result, err := lit.SelectSingleNamed[models.CountResult](db.TelemetryDB,+ "SELECT count(*) as count FROM sessions WHERE project_id = :project_id AND started_at >= :start AND started_at <= :end",+ lit.P{"project_id": projectId, "start": start.UTC(), "end": end.UTC()})+ if err != nil {+ return 0, err+ }+ if result == nil {+ return 0, nil+ }+ return int64(result.Count), nil+}++func (r *sessionRepository) FindAll(ctx context.Context, projectId uuid.UUID, fromDate, toDate time.Time, page, pageSize int, orderBy string, sortDirection string, search string, attributeFilters []shared.SessionAttributeFilter) ([]models.Session, int64, error) {+ whereExtra, extraParams := buildSessionFilterClauseDuckDB(search, attributeFilters)++ countQuery := "SELECT count(*) as count FROM sessions WHERE project_id = :project_id AND started_at >= :start AND started_at <= :end" + whereExtra+ countParams := lit.P{+ "project_id": projectId,+ "start": fromDate.UTC(),+ "end": toDate.UTC(),+ }+ for k, v := range extraParams {+ countParams[k] = v+ }+ countResult, err := lit.SelectSingleNamed[models.CountResult](db.TelemetryDB, countQuery, countParams)+ if err != nil {+ return nil, 0, err+ }+ var count int64+ if countResult != nil {+ count = int64(countResult.Count)+ }++ allowedOrderBy := map[string]bool{+ "started_at": true,+ "duration": true,+ }+ if !allowedOrderBy[orderBy] {+ orderBy = "started_at"+ }+ sortDir := "DESC"+ if sortDirection == "asc" {+ sortDir = "ASC"+ }++ offset := (page - 1) * pageSize+ query := "SELECT id, project_id, started_at, ended_at, duration, client_ip, attributes, app_version, server_name, distributed_trace_id FROM sessions WHERE project_id = :project_id AND started_at >= :start AND started_at <= :end" + whereExtra + " ORDER BY " + orderBy + " " + sortDir + " LIMIT :limit OFFSET :offset"++ queryParams := lit.P{+ "project_id": projectId,+ "start": fromDate.UTC(),+ "end": toDate.UTC(),+ "limit": pageSize,+ "offset": offset,+ }+ for k, v := range extraParams {+ queryParams[k] = v+ }+ rows, err := lit.SelectNamed[sessionRow](db.TelemetryDB, query, queryParams)+ if err != nil {+ return nil, 0, err+ }++ sessions := make([]models.Session, 0, len(rows))+ for _, row := range rows {+ sessions = append(sessions, row.toModel())+ }+ return sessions, count, nil+}++// buildSessionFilterClauseDuckDB produces a WHERE fragment + named params+// mirroring the ClickHouse helper: search must be a valid UUID for an exact+// id match (anything else is ignored), and each attribute filter becomes an+// exact match against `json_extract_string(attributes, '$.<key>')`.+func buildSessionFilterClauseDuckDB(search string, filters []shared.SessionAttributeFilter) (string, lit.P) {+ var sb strings.Builder+ params := lit.P{}+ if s := strings.TrimSpace(search); s != "" {+ if id, err := uuid.Parse(s); err == nil {+ sb.WriteString(" AND id = :search_id")+ params["search_id"] = id+ }+ }+ for i, f := range filters {+ if f.Key == "" {+ continue+ }+ keyParam := fmt.Sprintf("attr_k_%d", i)+ valParam := fmt.Sprintf("attr_v_%d", i)+ sb.WriteString(" AND json_extract_string(attributes, '$.\"' || :")+ sb.WriteString(keyParam)+ sb.WriteString(" || '\"') = :")+ sb.WriteString(valParam)+ params[keyParam] = f.Key+ params[valParam] = f.Value+ }+ return sb.String(), params+}++func (r *sessionRepository) FindById(ctx context.Context, projectId, sessionId uuid.UUID, startedAt *time.Time) (*models.Session, error) {+ query := "SELECT id, project_id, started_at, ended_at, duration, client_ip, attributes, app_version, server_name, distributed_trace_id FROM sessions WHERE project_id = :project_id AND id = :id"+ params := lit.P{"project_id": projectId, "id": sessionId}+ if startedAt != nil {+ from, to := shared.TraceWindowBounds(*startedAt)+ query += " AND started_at >= :from AND started_at <= :to"+ params["from"] = from.UTC()+ params["to"] = to.UTC()+ }+ query += " LIMIT 1"++ row, err := lit.SelectSingleNamed[sessionRow](db.TelemetryDB, query, params)+ if err != nil {+ return nil, err+ }+ if row == nil {+ return nil, nil+ }+ s := row.toModel()+ return &s, nil+}++var SessionRepository = &sessionRepository{}diff --git a/backend/app/repositories/telemetry/duckdb/session_recording.repository.go b/backend/app/repositories/telemetry/duckdb/session_recording.repository.gonew file mode 100644index 00000000..715d0e9e--- /dev/null+++ b/backend/app/repositories/telemetry/duckdb/session_recording.repository.go@@ -0,0 +1,114 @@+//go:build telemetry_duckdb++package duckdb++import (+ "context"+ "database/sql"+ "fmt"++ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/sqlitetypes"++ "github.com/duckdb/duckdb-go/v2"+ "github.com/google/uuid"+ "github.com/tracewayapp/lit/v2"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"+)++type sessionRecording struct {+ Id uuid.UUID `lit:"id"`+ ProjectId uuid.UUID `lit:"project_id"`+ ExceptionId uuid.UUID `lit:"exception_id"`+ SessionId *uuid.UUID `lit:"session_id"`+ SegmentIndex int32 `lit:"segment_index"`+ FilePath string `lit:"file_path"`+ RecordedAt sqlitetypes.SQLiteTime `lit:"recorded_at"`+}++func init() {+ models.ExtensionModelRegistrations = append(models.ExtensionModelRegistrations, func(driver lit.Driver) {+ lit.RegisterModel[sessionRecording](driver)+ })+}++type sessionRecordingRepository struct{}++func (r *sessionRecordingRepository) InsertAsync(ctx context.Context, recordings []models.SessionRecording) error {+ if len(recordings) == 0 {+ return nil+ }++ // Unlike the other telemetry tables, dropped rows must surface as an error:+ // the recordings uploader counts an InsertAsync failure in its failed metric,+ // and a silently missing row means an orphaned blob in storage.+ dropped := 0+ err := withAppender(ctx, "session_recordings", func(appender *duckdb.Appender) {+ for _, rec := range recordings {+ var sessionId *string+ if rec.SessionId != nil {+ s := rec.SessionId.String()+ sessionId = &s+ }+ // DDL column order: id, project_id, exception_id, file_path, recorded_at, session_id, segment_index+ if err := appender.AppendRow(+ rec.Id.String(),+ rec.ProjectId.String(),+ rec.ExceptionId.String(),+ rec.FilePath,+ rec.RecordedAt.UTC(),+ nullableString(sessionId),+ int64(rec.SegmentIndex),+ ); err != nil {+ captureDroppedRow("session_recordings", err)+ dropped+++ }+ }+ })+ if err != nil {+ return err+ }+ if dropped > 0 {+ return fmt.Errorf("session_recordings insert: dropped %d of %d rows", dropped, len(recordings))+ }+ return nil+}++func (r *sessionRecordingRepository) FindByExceptionId(ctx context.Context, projectId uuid.UUID, exceptionId uuid.UUID) (string, error) {+ result, err := lit.SelectSingleNamed[sqlitetypes.FilePathResult](db.TelemetryDB,+ "SELECT file_path FROM session_recordings WHERE project_id = :project_id AND exception_id = :exception_id ORDER BY recorded_at DESC LIMIT 1",+ lit.P{"project_id": projectId, "exception_id": exceptionId})+ if err != nil {+ return "", err+ }+ if result == nil {+ return "", sql.ErrNoRows+ }+ return result.FilePath, nil+}++// FindBySessionId returns all recording segments for a session ordered by segment_index.+func (r *sessionRecordingRepository) FindBySessionId(ctx context.Context, projectId, sessionId uuid.UUID) ([]models.SessionRecording, error) {+ rows, err := lit.SelectNamed[sessionRecording](db.TelemetryDB,+ "SELECT id, project_id, exception_id, session_id, segment_index, file_path, recorded_at FROM session_recordings WHERE project_id = :project_id AND session_id = :session_id ORDER BY segment_index ASC, recorded_at ASC",+ lit.P{"project_id": projectId, "session_id": sessionId})+ if err != nil {+ return nil, err+ }++ out := make([]models.SessionRecording, 0, len(rows))+ for _, row := range rows {+ out = append(out, models.SessionRecording{+ Id: row.Id,+ ProjectId: row.ProjectId,+ ExceptionId: row.ExceptionId,+ SessionId: row.SessionId,+ SegmentIndex: row.SegmentIndex,+ FilePath: row.FilePath,+ RecordedAt: row.RecordedAt.Time,+ })+ }+ return out, nil+}++var SessionRecordingRepository = &sessionRecordingRepository{}diff --git a/backend/app/repositories/telemetry/duckdb/span.repository.go b/backend/app/repositories/telemetry/duckdb/span.repository.gonew file mode 100644index 00000000..7f9d5bd7--- /dev/null+++ b/backend/app/repositories/telemetry/duckdb/span.repository.go@@ -0,0 +1,118 @@+//go:build telemetry_duckdb++package duckdb++import (+ "context"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/shared"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/sqlitetypes"+ "time"++ "github.com/duckdb/duckdb-go/v2"+ "github.com/google/uuid"+ "github.com/tracewayapp/lit/v2"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"+)++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 sqlitetypes.SQLiteTime `lit:"start_time"`+ Duration int64 `lit:"duration"`+ RecordedAt sqlitetypes.SQLiteTime `lit:"recorded_at"`+ ParentSpanId *uuid.UUID `lit:"parent_span_id"`+ Attributes sqlitetypes.SQLiteJSONMap `lit:"attributes"`+}++func init() {+ models.ExtensionModelRegistrations = append(models.ExtensionModelRegistrations, func(driver lit.Driver) {+ lit.RegisterModel[span](driver)+ })+}++func (r *span) toModel() models.Span {+ s := models.Span{+ Id: r.Id,+ TraceId: r.TraceId,+ ProjectId: r.ProjectId,+ Name: r.Name,+ StartTime: r.StartTime.Time,+ Duration: time.Duration(r.Duration),+ RecordedAt: r.RecordedAt.Time,+ ParentSpanId: r.ParentSpanId,+ }+ if r.Attributes != nil {+ s.Attributes = map[string]string(r.Attributes)+ }+ return s+}++type spanRepository struct{}++func (r *spanRepository) InsertAsync(ctx context.Context, spans []models.Span) error {+ if len(spans) == 0 {+ return nil+ }++ return withAppender(ctx, "spans", func(appender *duckdb.Appender) {++ for _, s := range spans {+ attributesJSON, err := attrJSON(s.Attributes)+ if err != nil {+ captureDroppedRow("spans", err)+ continue+ }++ var parentSpanId *string+ if s.ParentSpanId != nil {+ v := s.ParentSpanId.String()+ parentSpanId = &v+ }++ if err := appender.AppendRow(+ s.Id.String(),+ s.TraceId.String(),+ s.ProjectId.String(),+ s.Name,+ s.StartTime.UTC(),+ int64(s.Duration),+ s.RecordedAt.UTC(),+ nullableString(parentSpanId),+ attributesJSON,+ ); err != nil {+ captureDroppedRow("spans", err)+ }+ }++ })+}++func (r *spanRepository) FindByTraceId(ctx context.Context, projectId, traceId uuid.UUID, recordedAt *time.Time) ([]models.Span, error) {+ query := `SELECT id, trace_id, project_id, name, start_time, duration, recorded_at, parent_span_id, attributes+ FROM spans+ WHERE project_id = :project_id AND trace_id = :trace_id`+ params := lit.P{"project_id": projectId, "trace_id": traceId}+ if recordedAt != nil {+ from, to := shared.TraceWindowBounds(*recordedAt)+ query += ` AND recorded_at >= :from AND recorded_at <= :to`+ params["from"] = from.UTC()+ params["to"] = to.UTC()+ }+ query += ` ORDER BY start_time ASC`++ rows, err := lit.SelectNamed[span](db.TelemetryDB, query, params)+ if err != nil {+ return nil, err+ }++ spans := make([]models.Span, 0, len(rows))+ for _, row := range rows {+ spans = append(spans, row.toModel())+ }+ return spans, nil+}++var SpanRepository = &spanRepository{}diff --git a/backend/app/repositories/telemetry/duckdb/task.repository.go b/backend/app/repositories/telemetry/duckdb/task.repository.gonew file mode 100644index 00000000..71d30be7--- /dev/null+++ b/backend/app/repositories/telemetry/duckdb/task.repository.go@@ -0,0 +1,547 @@+//go:build telemetry_duckdb++package duckdb++import (+ "context"+ "database/sql"+ "fmt"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/shared"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/sqlitetypes"+ "sort"+ "strings"+ "time"++ "github.com/duckdb/duckdb-go/v2"+ "github.com/google/uuid"+ "github.com/tracewayapp/lit/v2"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"+)++type task struct {+ Id uuid.UUID `lit:"id"`+ ProjectId uuid.UUID `lit:"project_id"`+ TaskName string `lit:"task_name"`+ Duration int64 `lit:"duration"`+ RecordedAt sqlitetypes.SQLiteTime `lit:"recorded_at"`+ ClientIP string `lit:"client_ip"`+ Attributes sqlitetypes.SQLiteJSONMap `lit:"attributes"`+ AppVersion string `lit:"app_version"`+ ServerName string `lit:"server_name"`+ DistributedTraceId *uuid.UUID `lit:"distributed_trace_id"`+ SpanId *uuid.UUID `lit:"span_id"`+ IsRoot bool `lit:"is_root"`+}++type taskGroupRow struct {+ TaskName string `lit:"task_name"`+ Count uint64 `lit:"count"`+ AvgDuration float64 `lit:"avg_duration"`+ LastSeen time.Time `lit:"last_seen"`+ HasRoot bool `lit:"has_root"`+ HasNonRoot bool `lit:"has_non_root"`+ P50 float64 `lit:"p50"`+ P95 float64 `lit:"p95"`+}++type taskCountStatsRow struct {+ Count int64 `lit:"count"`+ AvgDurMs float64 `lit:"avg_dur_ms"`+}++func init() {+ models.ExtensionModelRegistrations = append(models.ExtensionModelRegistrations, func(driver lit.Driver) {+ lit.RegisterModel[task](driver)+ lit.RegisterModel[taskGroupRow](driver)+ lit.RegisterModel[taskCountStatsRow](driver)+ })+}++func (r *task) toModel() models.Task {+ t := models.Task{+ Id: r.Id,+ ProjectId: r.ProjectId,+ TaskName: r.TaskName,+ Duration: time.Duration(r.Duration),+ RecordedAt: r.RecordedAt.Time,+ ClientIP: r.ClientIP,+ AppVersion: r.AppVersion,+ ServerName: r.ServerName,+ DistributedTraceId: r.DistributedTraceId,+ SpanId: r.SpanId,+ IsRoot: r.IsRoot,+ }+ if r.Attributes != nil {+ t.Attributes = map[string]string(r.Attributes)+ }+ return t+}++type taskRepository struct{}++func (e *taskRepository) InsertAsync(ctx context.Context, lines []models.Task) error {+ if len(lines) == 0 {+ return nil+ }++ return withAppender(ctx, "tasks", func(appender *duckdb.Appender) {++ for _, t := range lines {+ attributesJSON, err := attrJSON(t.Attributes)+ if err != nil {+ captureDroppedRow("tasks", err)+ continue+ }++ var distributedTraceId *string+ if t.DistributedTraceId != nil {+ s := t.DistributedTraceId.String()+ distributedTraceId = &s+ }++ var spanId *string+ if t.SpanId != nil {+ s := t.SpanId.String()+ spanId = &s+ }++ isRoot := boolToInt(t.IsRoot)++ if err := appender.AppendRow(+ t.Id.String(),+ t.ProjectId.String(),+ t.TaskName,+ int64(t.Duration),+ t.RecordedAt.UTC(),+ t.ClientIP,+ attributesJSON,+ t.AppVersion,+ t.ServerName,+ nullableString(distributedTraceId),+ nullableString(spanId),+ isRoot,+ ); err != nil {+ captureDroppedRow("tasks", err)+ }+ }++ })+}++func (e *taskRepository) CountBetween(ctx context.Context, projectId uuid.UUID, start, end time.Time) (int64, error) {+ result, err := lit.SelectSingleNamed[models.CountResult](db.TelemetryDB,+ "SELECT COUNT(*) AS count FROM tasks WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to",+ lit.P{"project_id": projectId, "from": start.UTC(), "to": end.UTC()})+ if err != nil {+ return 0, err+ }+ if result == nil {+ return 0, nil+ }+ return int64(result.Count), nil+}++func (e *taskRepository) FindAll(ctx context.Context, projectId uuid.UUID, fromDate, toDate time.Time, page, pageSize int, orderBy string) ([]models.Task, int64, error) {+ countResult, err := lit.SelectSingleNamed[models.CountResult](db.TelemetryDB,+ "SELECT COUNT(*) AS count FROM tasks WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to",+ lit.P{"project_id": projectId, "from": fromDate.UTC(), "to": toDate.UTC()})+ if err != nil {+ return nil, 0, err+ }+ count := int64(0)+ if countResult != nil {+ count = int64(countResult.Count)+ }++ offset := (page - 1) * pageSize++ allowedOrderBy := map[string]bool{"recorded_at": true, "duration": true}+ if !allowedOrderBy[orderBy] {+ orderBy = "recorded_at"+ }++ rows, err := lit.SelectNamed[task](db.TelemetryDB,+ fmt.Sprintf(`SELECT id, project_id, task_name, duration, recorded_at, client_ip, attributes, app_version, server_name, distributed_trace_id+ FROM tasks WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to+ ORDER BY %s DESC LIMIT :limit OFFSET :offset`, orderBy),+ lit.P{"project_id": projectId, "from": fromDate.UTC(), "to": toDate.UTC(), "limit": pageSize, "offset": offset})+ if err != nil {+ return nil, 0, err+ }++ tasks := make([]models.Task, 0, len(rows))+ for _, row := range rows {+ tasks = append(tasks, row.toModel())+ }++ return tasks, count, nil+}++func (e *taskRepository) FindGroupedByTaskName(ctx context.Context, projectId uuid.UUID, fromDate, toDate time.Time, page, pageSize int, orderBy string, sortDirection string, search string, rootFilter string) ([]models.TaskStats, int64, error) {+ params := lit.P{"project_id": projectId, "from": fromDate.UTC(), "to": toDate.UTC()}+ whereClause := "project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to"+ if search != "" {+ whereClause += " AND INSTR(LOWER(task_name), LOWER(:search)) > 0"+ params["search"] = search+ }+ whereClause += shared.RootFilterClause("is_root", rootFilter)++ needsGoSort := orderBy == "p50_duration" || orderBy == "p95_duration" || orderBy == "impact"++ // The Go-sort path fetches every group, so the total falls out of the+ // result set; the COUNT(DISTINCT) pre-scan is only needed when the+ // database paginates.+ totalCount := int64(0)+ if !needsGoSort {+ totalResult, err := lit.SelectSingleNamed[models.CountResult](db.TelemetryDB,+ "SELECT COUNT(DISTINCT task_name) AS count FROM tasks WHERE "+whereClause,+ params)+ if err != nil {+ return nil, 0, err+ }+ if totalResult != nil {+ totalCount = int64(totalResult.Count)+ }+ }++ sortDir := "DESC"+ if sortDirection == "asc" {+ sortDir = "ASC"+ }++ offset := (page - 1) * pageSize++ var baseQuery string++ groupedCols := `task_name, COUNT(*) as count, AVG(duration) as avg_duration, MAX(recorded_at) as last_seen,+ MAX(is_root) as has_root, MAX(CASE WHEN is_root = 0 THEN 1 ELSE 0 END) as has_non_root,+ quantile_cont(duration, 0.5) as p50, quantile_cont(duration, 0.95) as p95`++ if needsGoSort {+ baseQuery = `SELECT ` + groupedCols + `+ FROM tasks WHERE ` + whereClause + `+ GROUP BY task_name`+ } else {+ orderExpr := map[string]string{"count": "count", "last_seen": "last_seen"}+ expr, ok := orderExpr[orderBy]+ if !ok {+ expr = "count"+ }+ baseQuery = fmt.Sprintf(`SELECT `+groupedCols+`+ FROM tasks WHERE `+whereClause+`+ GROUP BY task_name ORDER BY %s %s LIMIT :limit OFFSET :offset`, expr, sortDir)+ params["limit"] = pageSize+ params["offset"] = offset+ }++ groups, err := lit.SelectNamed[taskGroupRow](db.TelemetryDB, baseQuery, params)+ if err != nil {+ return nil, 0, err+ }++ var stats []models.TaskStats+ for _, g := range groups {+ stats = append(stats, models.TaskStats{+ TaskName: g.TaskName,+ Count: g.Count,+ P50Duration: time.Duration(g.P50),+ P95Duration: time.Duration(g.P95),+ AvgDuration: time.Duration(g.AvgDuration),+ LastSeen: g.LastSeen,+ HasRoot: g.HasRoot,+ HasNonRoot: g.HasNonRoot,+ })+ }++ if needsGoSort {+ totalCount = int64(len(stats))+ switch orderBy {+ case "p50_duration":+ sort.Slice(stats, func(i, j int) bool {+ if sortDir == "ASC" {+ return stats[i].P50Duration < stats[j].P50Duration+ }+ return stats[i].P50Duration > stats[j].P50Duration+ })+ case "p95_duration":+ sort.Slice(stats, func(i, j int) bool {+ if sortDir == "ASC" {+ return stats[i].P95Duration < stats[j].P95Duration+ }+ return stats[i].P95Duration > stats[j].P95Duration+ })+ case "impact":+ sort.Slice(stats, func(i, j int) bool {+ impactI := float64(stats[i].Count) * float64(stats[i].P95Duration-stats[i].P50Duration)+ impactJ := float64(stats[j].Count) * float64(stats[j].P95Duration-stats[j].P50Duration)+ if sortDir == "ASC" {+ return impactI < impactJ+ }+ return impactI > impactJ+ })+ }++ end := offset + pageSize+ if end > len(stats) {+ end = len(stats)+ }+ if offset > len(stats) {+ stats = nil+ } else {+ stats = stats[offset:end]+ }+ }++ return stats, totalCount, nil+}++func (e *taskRepository) FindByTaskName(ctx context.Context, projectId uuid.UUID, taskName string, fromDate, toDate time.Time, page, pageSize int, orderBy string, sortDirection string) ([]models.Task, int64, error) {+ params := lit.P{"project_id": projectId, "task_name": taskName, "from": fromDate.UTC(), "to": toDate.UTC()}++ countResult, err := lit.SelectSingleNamed[models.CountResult](db.TelemetryDB,+ "SELECT COUNT(*) AS count FROM tasks WHERE project_id = :project_id AND task_name = :task_name AND recorded_at >= :from AND recorded_at <= :to",+ params)+ if err != nil {+ return nil, 0, err+ }+ count := int64(0)+ if countResult != nil {+ count = int64(countResult.Count)+ }++ offset := (page - 1) * pageSize++ allowedOrderBy := map[string]bool{"recorded_at": true, "duration": true}+ if !allowedOrderBy[orderBy] {+ orderBy = "recorded_at"+ }++ sortDir := "DESC"+ if sortDirection == "asc" {+ sortDir = "ASC"+ }++ rows, err := lit.SelectNamed[task](db.TelemetryDB,+ fmt.Sprintf(`SELECT id, project_id, task_name, duration, recorded_at, client_ip, attributes, app_version, server_name, distributed_trace_id+ FROM tasks WHERE project_id = :project_id AND task_name = :task_name AND recorded_at >= :from AND recorded_at <= :to+ ORDER BY %s %s LIMIT :limit OFFSET :offset`, orderBy, sortDir),+ lit.P{"project_id": projectId, "task_name": taskName, "from": fromDate.UTC(), "to": toDate.UTC(), "limit": pageSize, "offset": offset})+ if err != nil {+ return nil, 0, err+ }++ tasks := make([]models.Task, 0, len(rows))+ for _, row := range rows {+ tasks = append(tasks, row.toModel())+ }++ return tasks, count, nil+}++func (e *taskRepository) FindById(ctx context.Context, projectId, taskId uuid.UUID, recordedAt *time.Time) (*models.Task, error) {+ query := `SELECT id, project_id, task_name, duration, recorded_at, client_ip, attributes, app_version, server_name, distributed_trace_id, span_id, is_root+ FROM tasks WHERE project_id = :project_id AND id = :id`+ params := lit.P{"project_id": projectId, "id": taskId}+ if recordedAt != nil {+ from, to := shared.TraceWindowBounds(*recordedAt)+ query += ` AND recorded_at >= :from AND recorded_at <= :to`+ params["from"] = from.UTC()+ params["to"] = to.UTC()+ }+ query += ` LIMIT 1`++ row, err := lit.SelectSingleNamed[task](db.TelemetryDB, query, params)+ if err != nil {+ return nil, err+ }+ if row == nil {+ return nil, nil+ }+ t := row.toModel()+ return &t, nil+}++func (e *taskRepository) CountByHour(ctx context.Context, projectId uuid.UUID, start, end time.Time) ([]models.TimeSeriesPoint, error) {+ return queryTaskTimeSeries(ctx,+ `SELECT `+timeBucketExpr("recorded_at", 3600)+` as bucket, CAST(COUNT(*) AS DOUBLE) as agg_value+ FROM tasks WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to+ GROUP BY bucket ORDER BY bucket ASC`,+ lit.P{"project_id": projectId, "from": start.UTC(), "to": end.UTC()})+}++func (e *taskRepository) AvgDurationByHour(ctx context.Context, projectId uuid.UUID, start, end time.Time) ([]models.TimeSeriesPoint, error) {+ return queryTaskTimeSeries(ctx,+ `SELECT `+timeBucketExpr("recorded_at", 3600)+` as bucket, AVG(duration) / 1000000.0 as agg_value+ FROM tasks WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to+ GROUP BY bucket ORDER BY bucket ASC`,+ lit.P{"project_id": projectId, "from": start.UTC(), "to": end.UTC()})+}++func (e *taskRepository) CountByInterval(ctx context.Context, projectId uuid.UUID, start, end time.Time, intervalMinutes int) ([]models.TimeSeriesPoint, error) {+ return queryTaskTimeSeries(ctx,+ `SELECT `+timeBucketExpr("recorded_at", intervalMinutes*60)+` as bucket, CAST(COUNT(*) AS DOUBLE) as agg_value+ FROM tasks WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to+ GROUP BY bucket ORDER BY bucket ASC`,+ lit.P{"project_id": projectId, "from": start.UTC(), "to": end.UTC()})+}++func (e *taskRepository) AvgDurationByInterval(ctx context.Context, projectId uuid.UUID, start, end time.Time, intervalMinutes int) ([]models.TimeSeriesPoint, error) {+ return queryTaskTimeSeries(ctx,+ `SELECT `+timeBucketExpr("recorded_at", intervalMinutes*60)+` as bucket, AVG(duration) / 1000000.0 as agg_value+ FROM tasks WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to+ GROUP BY bucket ORDER BY bucket ASC`,+ lit.P{"project_id": projectId, "from": start.UTC(), "to": end.UTC()})+}++func (e *taskRepository) FindWorstTasks(ctx context.Context, projectId uuid.UUID, start, end time.Time, limit int) ([]models.TaskStats, error) {+ params := lit.P{"project_id": projectId, "from": start.UTC(), "to": end.UTC()}++ groups, err := lit.SelectNamed[taskGroupRow](db.TelemetryDB,+ `SELECT task_name, COUNT(*) as count, AVG(duration) as avg_duration, MAX(recorded_at) as last_seen,+ quantile_cont(duration, 0.5) as p50, quantile_cont(duration, 0.95) as p95+ FROM tasks WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to+ GROUP BY task_name`,+ params)+ if err != nil {+ return nil, err+ }++ var stats []models.TaskStats+ for _, g := range groups {+ stats = append(stats, models.TaskStats{+ TaskName: g.TaskName,+ Count: g.Count,+ P50Duration: time.Duration(g.P50),+ P95Duration: time.Duration(g.P95),+ AvgDuration: time.Duration(g.AvgDuration),+ LastSeen: g.LastSeen,+ })+ }++ sort.Slice(stats, func(i, j int) bool {+ impactI := float64(stats[i].Count) * float64(stats[i].P95Duration-stats[i].P50Duration)+ impactJ := float64(stats[j].Count) * float64(stats[j].P95Duration-stats[j].P50Duration)+ return impactI > impactJ+ })++ if limit > len(stats) {+ limit = len(stats)+ }+ return stats[:limit], nil+}++func (e *taskRepository) GetTaskStats(ctx context.Context, projectId uuid.UUID, taskName string, start, end time.Time) (*models.TaskDetailStats, error) {+ params := lit.P{"project_id": projectId, "task_name": taskName, "from": start.UTC(), "to": end.UTC()}++ durationMinutes := end.Sub(start).Minutes()+ if durationMinutes < 1 {+ durationMinutes = 1+ }++ statsRow, err := lit.SelectSingleNamed[taskCountStatsRow](db.TelemetryDB,+ "SELECT COUNT(*) AS count, CASE WHEN COUNT(*) > 0 THEN AVG(duration) / 1000000.0 ELSE 0 END AS avg_dur_ms FROM tasks WHERE project_id = :project_id AND task_name = :task_name AND recorded_at >= :from AND recorded_at <= :to",+ params)+ if err != nil {+ return nil, err+ }+ if statsRow == nil {+ return &models.TaskDetailStats{}, nil+ }++ pctQuery, pctArgs, err := lit.ParseNamedQuery(db.Driver,+ `SELECT quantile_cont(duration, 0.5) AS p50, quantile_cont(duration, 0.95) AS p95, quantile_cont(duration, 0.99) AS p99+ FROM tasks WHERE project_id = :project_id AND task_name = :task_name AND recorded_at >= :from AND recorded_at <= :to`,+ params)+ if err != nil {+ return nil, err+ }++ var p50, p95, p99 sql.NullFloat64+ if err := db.TelemetryDB.QueryRowContext(ctx, pctQuery, pctArgs...).Scan(&p50, &p95, &p99); err != nil {+ return nil, err+ }++ nsToMs := 1000000.0++ return &models.TaskDetailStats{+ Count: statsRow.Count,+ AvgDuration: statsRow.AvgDurMs,+ MedianDuration: p50.Float64 / nsToMs,+ P95Duration: p95.Float64 / nsToMs,+ P99Duration: p99.Float64 / nsToMs,+ Throughput: float64(statsRow.Count) / durationMinutes,+ }, nil+}++func (e *taskRepository) FindByDistributedTraceId(ctx context.Context, distributedTraceId uuid.UUID, projectIds []uuid.UUID, recordedAt *time.Time) ([]models.Task, error) {+ if len(projectIds) == 0 {+ return nil, nil+ }+ params := lit.P{"trace_id": distributedTraceId}+ placeholders := make([]string, len(projectIds))+ for i, pid := range projectIds {+ key := fmt.Sprintf("pid_%d", i)+ placeholders[i] = ":" + key+ params[key] = pid+ }+ query := `SELECT id, project_id, task_name, duration, recorded_at, client_ip, attributes, app_version, server_name, distributed_trace_id+ FROM tasks WHERE distributed_trace_id = :trace_id AND project_id IN (` + strings.Join(placeholders, ",") + `)`+ if recordedAt != nil {+ from, to := shared.DistributedTraceWindowBounds(*recordedAt)+ query += ` AND recorded_at >= :from AND recorded_at <= :to`+ params["from"] = from.UTC()+ params["to"] = to.UTC()+ }+ query += ` ORDER BY recorded_at ASC`++ parsedQuery, args, err := lit.ParseNamedQuery(db.Driver, query, params)+ if err != nil {+ return nil, err+ }++ sqlRows, err := db.TelemetryDB.QueryContext(ctx, parsedQuery, args...)+ if err != nil {+ return nil, err+ }+ defer sqlRows.Close()++ var tasks []models.Task+ for sqlRows.Next() {+ var row task+ if err := sqlRows.Scan(&row.Id, &row.ProjectId, &row.TaskName, &row.Duration, &row.RecordedAt, &row.ClientIP, &row.Attributes, &row.AppVersion, &row.ServerName, &row.DistributedTraceId); err != nil {+ return nil, err+ }+ tasks = append(tasks, row.toModel())+ }+ return tasks, nil+}++// queryTaskTimeSeries runs a time-bucketed aggregation and scans the bucket as a+// native TIMESTAMP (time.Time) — DuckDB returns TIMESTAMP columns directly as+// time.Time, so no string parsing of the bucket is needed (unlike the SQLite path).+func queryTaskTimeSeries(ctx context.Context, query string, params lit.P) ([]models.TimeSeriesPoint, error) {+ parsedQuery, args, err := lit.ParseNamedQuery(db.Driver, query, params)+ if err != nil {+ return nil, err+ }++ rows, err := db.TelemetryDB.QueryContext(ctx, parsedQuery, args...)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ points := make([]models.TimeSeriesPoint, 0)+ for rows.Next() {+ var bucket time.Time+ var value float64+ if err := rows.Scan(&bucket, &value); err != nil {+ return nil, err+ }+ points = append(points, models.TimeSeriesPoint{Timestamp: bucket, Value: value})+ }+ return points, nil+}++var TaskRepository = &taskRepository{}diff --git a/backend/app/repositories/endpoint_repository_test.go b/backend/app/repositories/telemetry/endpoint_repository_test.gosimilarity index 96%rename from backend/app/repositories/endpoint_repository_test.gorename to backend/app/repositories/telemetry/endpoint_repository_test.goindex b0601d12..a56f0416 100644--- a/backend/app/repositories/endpoint_repository_test.go+++ b/backend/app/repositories/telemetry/endpoint_repository_test.go@@ -1,4 +1,4 @@-package repositories+package telemetryimport ("context"@@ -450,3 +450,20 @@ func TestEndpointRepository_InsertEmpty(t *testing.T) {t.Fatalf("InsertAsync with empty slice should not error: %v", err)}}++func TestEndpointRepository_GetEndpointStats_EmptyWindow(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ now := time.Now().UTC()++ stats, err := EndpointRepository.GetEndpointStats(ctx, uuid.New(), "GET /api/none", now.Add(-time.Hour), now)+ if err != nil {+ t.Fatalf("GetEndpointStats failed: %v", err)+ }+ if stats.Count != 0 {+ t.Errorf("expected count 0, got %d", stats.Count)+ }+ if stats.IsStream {+ t.Errorf("expected IsStream false for empty window")+ }+}diff --git a/backend/app/repositories/exception_repository_test.go b/backend/app/repositories/telemetry/exception_repository_test.gosimilarity index 95%rename from backend/app/repositories/exception_repository_test.gorename to backend/app/repositories/telemetry/exception_repository_test.goindex be834c98..b0388076 100644--- a/backend/app/repositories/exception_repository_test.go+++ b/backend/app/repositories/telemetry/exception_repository_test.go@@ -1,4 +1,4 @@-package repositories+package telemetryimport ("context"@@ -97,6 +97,18 @@ func TestExceptionRepository_FindGrouped(t *testing.T) {if groups[0].Count != 3 {t.Errorf("expected count 3, got %d", groups[0].Count)}++ // A page past the last group must still report the full total.+ groups, total, err = ExceptionStackTraceRepository.FindGrouped(ctx, projectId, now.Add(-time.Hour), now.Add(time.Hour), 5, 10, "count", "", "", false)+ if err != nil {+ t.Fatalf("FindGrouped page-past-end failed: %v", err)+ }+ if total != 2 {+ t.Errorf("expected total 2 on page past end, got %d", total)+ }+ if len(groups) != 0 {+ t.Errorf("expected 0 group entries on page past end, got %d", len(groups))+ }}func TestExceptionRepository_FindGrouped_Search(t *testing.T) {diff --git a/backend/app/repositories/fired_notification_repository_test.go b/backend/app/repositories/telemetry/fired_notification_repository_test.gosimilarity index 97%rename from backend/app/repositories/fired_notification_repository_test.gorename to backend/app/repositories/telemetry/fired_notification_repository_test.goindex 6a82c688..db3f904d 100644--- a/backend/app/repositories/fired_notification_repository_test.go+++ b/backend/app/repositories/telemetry/fired_notification_repository_test.go@@ -1,4 +1,4 @@-package repositories+package telemetryimport ("context"diff --git a/backend/app/repositories/helpers_test.go b/backend/app/repositories/telemetry/helpers_test.gosimilarity index 81%rename from backend/app/repositories/helpers_test.gorename to backend/app/repositories/telemetry/helpers_test.goindex 417f8691..cfbc6a5b 100644--- a/backend/app/repositories/helpers_test.go+++ b/backend/app/repositories/telemetry/helpers_test.go@@ -1,4 +1,4 @@-package repositories+package telemetryimport ("math"@@ -44,6 +44,27 @@ func makeTask(projectId uuid.UUID, taskName string, duration time.Duration, reco}}+func makeAiTrace(projectId uuid.UUID, traceName string, duration time.Duration, totalTokens int64, totalCost float64, recordedAt time.Time) models.AiTrace {+ return models.AiTrace{+ Id: uuid.New(),+ ProjectId: projectId,+ RecordedAt: recordedAt,+ Duration: duration,+ StatusCode: 200,+ Model: "test-model",+ Provider: "test-provider",+ Operation: "chat",+ InputTokens: totalTokens / 2,+ OutputTokens: totalTokens - totalTokens/2,+ TotalTokens: totalTokens,+ TotalCost: totalCost,+ TraceName: traceName,+ ServerName: "test-server",+ AppVersion: "1.0.0",+ IsRoot: true,+ }+}+func makeException(projectId uuid.UUID, hash, stackTrace string, recordedAt time.Time) models.ExceptionStackTrace {return models.ExceptionStackTrace{Id: uuid.New(),diff --git a/backend/app/repositories/telemetry/log_record_repository_test.go b/backend/app/repositories/telemetry/log_record_repository_test.gonew file mode 100644index 00000000..1d717e4f--- /dev/null+++ b/backend/app/repositories/telemetry/log_record_repository_test.go@@ -0,0 +1,107 @@+package telemetry++import (+ "context"+ "testing"+ "time"++ "github.com/google/uuid"+ "github.com/tracewayapp/traceway/backend/app/models"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/shared"+)++func makeLogRecord(projectId uuid.UUID, severity uint8, body string, timestamp time.Time) models.LogRecord {+ return models.LogRecord{+ Id: uuid.New(),+ ProjectId: projectId,+ Timestamp: timestamp,+ SeverityText: "test",+ SeverityNumber: severity,+ ServiceName: "svc",+ Body: body,+ }+}++func TestLogRecordRepository_SearchPaginationTotal(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ now := truncateMs(time.Now().UTC())++ records := []models.LogRecord{+ makeLogRecord(projectId, 17, "error one", now),+ makeLogRecord(projectId, 17, "error two", now.Add(time.Second)),+ makeLogRecord(projectId, 9, "info one", now.Add(2*time.Second)),+ }+ if err := LogRecordRepository.InsertAsync(ctx, records); err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ base := shared.LogSearchParams{+ ProjectId: projectId,+ FromDate: now.Add(-time.Hour),+ ToDate: now.Add(time.Hour),+ PageSize: 2,+ }++ params := base+ params.Page = 1+ rows, total, err := LogRecordRepository.Search(ctx, params)+ if err != nil {+ t.Fatalf("Search page 1 failed: %v", err)+ }+ if total != 3 {+ t.Errorf("expected total 3, got %d", total)+ }+ if len(rows) != 2 {+ t.Errorf("expected 2 rows on page 1, got %d", len(rows))+ }++ params.Page = 2+ rows, total, err = LogRecordRepository.Search(ctx, params)+ if err != nil {+ t.Fatalf("Search page 2 failed: %v", err)+ }+ if total != 3 {+ t.Errorf("expected total 3 on page 2, got %d", total)+ }+ if len(rows) != 1 {+ t.Errorf("expected 1 row on page 2, got %d", len(rows))+ }++ // A page past the last row must still report the full total.+ params.Page = 5+ rows, total, err = LogRecordRepository.Search(ctx, params)+ if err != nil {+ t.Fatalf("Search page-past-end failed: %v", err)+ }+ if total != 3 {+ t.Errorf("expected total 3 on page past end, got %d", total)+ }+ if len(rows) != 0 {+ t.Errorf("expected 0 rows on page past end, got %d", len(rows))+ }++ params = base+ params.Page = 1+ params.MinSeverity = 17+ rows, total, err = LogRecordRepository.Search(ctx, params)+ if err != nil {+ t.Fatalf("Search severity filter failed: %v", err)+ }+ if total != 2 {+ t.Errorf("expected total 2 with severity filter, got %d", total)+ }+ if len(rows) != 2 {+ t.Errorf("expected 2 rows with severity filter, got %d", len(rows))+ }++ params.MinSeverity = 30+ rows, total, err = LogRecordRepository.Search(ctx, params)+ if err != nil {+ t.Fatalf("Search no-match failed: %v", err)+ }+ if total != 0 || len(rows) != 0 {+ t.Errorf("expected no rows and total 0, got %d rows total %d", len(rows), total)+ }+}diff --git a/backend/app/repositories/telemetry/metric_point.repository_duckdb_test.go b/backend/app/repositories/telemetry/metric_point.repository_duckdb_test.gonew file mode 100644index 00000000..0bfe77f1--- /dev/null+++ b/backend/app/repositories/telemetry/metric_point.repository_duckdb_test.go@@ -0,0 +1,119 @@+//go:build telemetry_duckdb++package telemetry++import (+ "context"+ "database/sql"+ "testing"+ "time"++ "github.com/duckdb/duckdb-go/v2"+ "github.com/google/uuid"+ "github.com/tracewayapp/lit/v2"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"+)++func setupDuckDB(t *testing.T) {+ t.Helper()+ connector, err := duckdb.NewConnector("", nil)+ if err != nil {+ t.Fatalf("NewConnector: %v", err)+ }+ telemetry := sql.OpenDB(connector)+ if _, err := telemetry.Exec(`CREATE TABLE metric_points (+ project_id VARCHAR NOT NULL,+ name VARCHAR NOT NULL DEFAULT '',+ value DOUBLE NOT NULL DEFAULT 0,+ tags VARCHAR NOT NULL DEFAULT '{}',+ recorded_at TIMESTAMP NOT NULL,+ server_name VARCHAR NOT NULL DEFAULT ''+ )`); err != nil {+ t.Fatalf("create table: %v", err)+ }++ db.DuckDBConnector = connector+ db.TelemetryDB = telemetry+ db.Driver = lit.SQLite+ models.Init(lit.SQLite)++ t.Cleanup(func() { telemetry.Close() })+}++func TestDuckDBMetricPointsRoundTrip(t *testing.T) {+ setupDuckDB(t)+ ctx := context.Background()+ repo := MetricPointRepository++ project := uuid.New()+ base := time.Date(2026, 6, 1, 12, 0, 0, 0, time.UTC)+ points := []models.MetricPoint{+ {ProjectId: project, Name: "cpu.used_pcnt", Value: 10, Tags: map[string]string{"server_name": "a"}, RecordedAt: base},+ {ProjectId: project, Name: "cpu.used_pcnt", Value: 30, Tags: map[string]string{"server_name": "a"}, RecordedAt: base.Add(10 * time.Second)},+ {ProjectId: project, Name: "cpu.used_pcnt", Value: 50, Tags: map[string]string{"server_name": "b"}, RecordedAt: base.Add(20 * time.Second)},+ }++ if err := repo.InsertAsync(ctx, points); err != nil {+ t.Fatalf("InsertAsync (appender): %v", err)+ }++ from := base.Add(-time.Hour)+ to := base.Add(time.Hour)++ avg, err := repo.GetAverageBetween(ctx, project, "cpu.used_pcnt", from, to)+ if err != nil {+ t.Fatalf("GetAverageBetween: %v", err)+ }+ if avg != 30 {+ t.Fatalf("avg = %v, want 30", avg)+ }++ // time_bucket over a 1-minute window collapses all three points into one bucket.+ series, err := repo.QueryTimeSeries(ctx, project, "cpu.used_pcnt", from, to, 1, "avg", nil, "")+ if err != nil {+ t.Fatalf("QueryTimeSeries: %v", err)+ }+ if len(series["__all__"]) != 1 || series["__all__"][0].Value != 30 {+ t.Fatalf("QueryTimeSeries __all__ = %+v, want one bucket value 30", series["__all__"])+ }++ // json_extract_string group-by splits the same window by server tag.+ grouped, err := repo.QueryTimeSeries(ctx, project, "cpu.used_pcnt", from, to, 1, "avg", nil, "server_name")+ if err != nil {+ t.Fatalf("QueryTimeSeries grouped: %v", err)+ }+ if len(grouped["a"]) != 1 || grouped["a"][0].Value != 20 {+ t.Fatalf("grouped[a] = %+v, want value 20", grouped["a"])+ }+ if len(grouped["b"]) != 1 || grouped["b"][0].Value != 50 {+ t.Fatalf("grouped[b] = %+v, want value 50", grouped["b"])+ }++ servers, err := repo.GetDistinctServers(ctx, project, from, to)+ if err != nil {+ t.Fatalf("GetDistinctServers: %v", err)+ }+ if len(servers) != 2 || servers[0] != "a" || servers[1] != "b" {+ t.Fatalf("servers = %v, want [a b]", servers)+ }++ metrics, err := repo.DiscoverMetrics(ctx, project, from, to)+ if err != nil {+ t.Fatalf("DiscoverMetrics: %v", err)+ }+ if len(metrics) != 1 || metrics[0].Name != "cpu.used_pcnt" {+ t.Fatalf("DiscoverMetrics = %+v, want one cpu.used_pcnt", metrics)+ }+ if len(metrics[0].TagKeys) != 1 || metrics[0].TagKeys[0] != "server_name" {+ t.Fatalf("DiscoverMetrics tag keys = %v, want [server_name]", metrics[0].TagKeys)+ }++ values, err := repo.DiscoverTagValues(ctx, project, "cpu.used_pcnt", "server_name", from, to)+ if err != nil {+ t.Fatalf("DiscoverTagValues: %v", err)+ }+ if len(values) != 2 || values[0] != "a" || values[1] != "b" {+ t.Fatalf("DiscoverTagValues = %v, want [a b]", values)+ }+}diff --git a/backend/app/repositories/metric_point_repository_test.go b/backend/app/repositories/telemetry/metric_point_repository_test.gosimilarity index 99%rename from backend/app/repositories/metric_point_repository_test.gorename to backend/app/repositories/telemetry/metric_point_repository_test.goindex 3126a0cc..df1e8adf 100644--- a/backend/app/repositories/metric_point_repository_test.go+++ b/backend/app/repositories/telemetry/metric_point_repository_test.go@@ -1,4 +1,4 @@-package repositories+package telemetryimport ("context"diff --git a/backend/app/repositories/profile_labels_test.go b/backend/app/repositories/telemetry/profile_labels_test.gosimilarity index 99%rename from backend/app/repositories/profile_labels_test.gorename to backend/app/repositories/telemetry/profile_labels_test.goindex 742f7e60..77a98b07 100644--- a/backend/app/repositories/profile_labels_test.go+++ b/backend/app/repositories/telemetry/profile_labels_test.go@@ -1,6 +1,6 @@-//go:build !pgch+//go:build !telemetry_ch-package repositories+package telemetryimport ("context"diff --git a/backend/app/repositories/profile_query_test.go b/backend/app/repositories/telemetry/profile_query_test.gosimilarity index 99%rename from backend/app/repositories/profile_query_test.gorename to backend/app/repositories/telemetry/profile_query_test.goindex e44a21d4..ed7bcd7f 100644--- a/backend/app/repositories/profile_query_test.go+++ b/backend/app/repositories/telemetry/profile_query_test.go@@ -1,6 +1,6 @@-//go:build !pgch+//go:build !telemetry_ch-package repositories+package telemetryimport ("context"diff --git a/backend/app/repositories/profile_repository_test.go b/backend/app/repositories/telemetry/profile_repository_test.gosimilarity index 98%rename from backend/app/repositories/profile_repository_test.gorename to backend/app/repositories/telemetry/profile_repository_test.goindex 448bc3ca..7102b59b 100644--- a/backend/app/repositories/profile_repository_test.go+++ b/backend/app/repositories/telemetry/profile_repository_test.go@@ -1,6 +1,6 @@-//go:build !pgch+//go:build !telemetry_ch-package repositories+package telemetryimport ("context"diff --git a/backend/app/repositories/session_recording_repository_test.go b/backend/app/repositories/telemetry/session_recording_repository_test.gosimilarity index 99%rename from backend/app/repositories/session_recording_repository_test.gorename to backend/app/repositories/telemetry/session_recording_repository_test.goindex 4bf3b0ca..4164eac9 100644--- a/backend/app/repositories/session_recording_repository_test.go+++ b/backend/app/repositories/telemetry/session_recording_repository_test.go@@ -1,4 +1,4 @@-package repositories+package telemetryimport ("context"diff --git a/backend/app/repositories/impact.go b/backend/app/repositories/telemetry/shared/impact.gosimilarity index 78%rename from backend/app/repositories/impact.gorename to backend/app/repositories/telemetry/shared/impact.goindex 7b27b98f..556bdc0d 100644--- a/backend/app/repositories/impact.go+++ b/backend/app/repositories/telemetry/shared/impact.go@@ -1,4 +1,4 @@-package repositories+package sharedimport ("fmt"@@ -233,3 +233,71 @@ func addCommas(n uint64) string {}return string(result)}++func ComputeImpactScore(endpoint string, total, satisfiedCount, toleratingCount, badCount, clientErrorCount uint64, p99Ns float64, offsetMs uint32) float64 {+ if total == 0 {+ return 0+ }++ totalF := float64(total)+ badF := float64(badCount)+ clientF := float64(clientErrorCount)+ offsetNs := float64(offsetMs) * 1_000_000++ apdexScore := 1.0 - (float64(satisfiedCount)+float64(toleratingCount)*0.5)/totalF++ badRate := badF / totalF+ var errorRateScore float64+ switch {+ case badRate > 0.33:+ errorRateScore = 0.75+ case badRate > 0.20:+ errorRateScore = 0.50+ case badRate > 0.10:+ errorRateScore = 0.25+ }++ adjustedP99 := p99Ns - offsetNs+ var p99Score float64+ switch {+ case adjustedP99 > 8_000_000_000:+ p99Score = 0.75+ case adjustedP99 > 6_000_000_000:+ p99Score = 0.50+ case adjustedP99 > 3_000_000_000:+ p99Score = 0.25+ }++ var clientErrorScore float64+ if endpoint != "UNMATCHED" && total > 10 {+ clientRate := clientF / totalF+ switch {+ case clientRate > 0.50:+ clientErrorScore = 0.75+ case clientRate > 0.25:+ clientErrorScore = 0.50+ }+ }++ var volumeScore float64+ switch {+ case badRate > 0.10 && badCount >= 500:+ volumeScore = 0.75+ case badRate > 0.10 && badCount >= 50:+ volumeScore = 0.50+ case badRate > 0.05 && badCount >= 2000:+ volumeScore = 0.75+ case badRate > 0.05 && badCount >= 500:+ volumeScore = 0.50+ case badRate > 0.05 && badCount >= 50:+ volumeScore = 0.25+ case badRate > 0.01 && badCount >= 10000:+ volumeScore = 0.75+ case badRate > 0.01 && badCount >= 2000:+ volumeScore = 0.50+ case badRate > 0.01 && badCount >= 500:+ volumeScore = 0.25+ }++ return math.Max(apdexScore, math.Max(errorRateScore, math.Max(p99Score, math.Max(clientErrorScore, volumeScore))))+}diff --git a/backend/app/repositories/percentile.go b/backend/app/repositories/telemetry/shared/percentile.gosimilarity index 75%rename from backend/app/repositories/percentile.gorename to backend/app/repositories/telemetry/shared/percentile.goindex 1dd167bc..712d3865 100644--- a/backend/app/repositories/percentile.go+++ b/backend/app/repositories/telemetry/shared/percentile.go@@ -1,6 +1,6 @@-package repositories+package shared-func computePercentile(sorted []float64, p float64) float64 {+func ComputePercentile(sorted []float64, p float64) float64 {n := len(sorted)if n == 0 {return 0diff --git a/backend/app/repositories/profile.repository_common.go b/backend/app/repositories/telemetry/shared/profile_common.gosimilarity index 74%rename from backend/app/repositories/profile.repository_common.gorename to backend/app/repositories/telemetry/shared/profile_common.goindex 09d0ca2a..ff35e5df 100644--- a/backend/app/repositories/profile.repository_common.go+++ b/backend/app/repositories/telemetry/shared/profile_common.go@@ -1,4 +1,4 @@-package repositories+package sharedimport ("strings"@@ -6,7 +6,7 @@ import ("github.com/tracewayapp/traceway/backend/app/models")-func normalizeSeriesPoints(points []models.TimeSeriesPoint, normalize, isGauge bool, intervalMinutes int) {+func NormalizeSeriesPoints(points []models.TimeSeriesPoint, normalize, isGauge bool, intervalMinutes int) {if !normalize || isGauge {return}@@ -19,7 +19,7 @@ func normalizeSeriesPoints(points []models.TimeSeriesPoint, normalize, isGauge b}}-func clampBreakdownLimit(limit int) int {+func ClampBreakdownLimit(limit int) int {if limit <= 0 {return 8}@@ -29,7 +29,7 @@ func clampBreakdownLimit(limit int) int {return limit}-func breakdownLabelKey(dimension string) (string, bool) {+func BreakdownLabelKey(dimension string) (string, bool) {const prefix = "label:"if !strings.HasPrefix(dimension, prefix) {return "", falsediff --git a/backend/app/repositories/profile.repository_labels.go b/backend/app/repositories/telemetry/shared/profile_labels.gosimilarity index 63%rename from backend/app/repositories/profile.repository_labels.gorename to backend/app/repositories/telemetry/shared/profile_labels.goindex 4957c680..b4e7688f 100644--- a/backend/app/repositories/profile.repository_labels.go+++ b/backend/app/repositories/telemetry/shared/profile_labels.go@@ -1,16 +1,16 @@-package repositories+package sharedimport ("context""sync""time"-- "github.com/google/uuid")const discoverLabelsTimeout = 10 * time.Second-func (r *profileRepository) DiscoverLabels(ctx context.Context, projectId uuid.UUID, service, profileType string, from, to time.Time, allowKeys []string) (map[string][]string, error) {+// DiscoverLabels fans out over allowKeys and collects the distinct values per+// key; distinct is the backend-specific query for a single key.+func DiscoverLabels(ctx context.Context, allowKeys []string, distinct func(ctx context.Context, key string) ([]string, error)) (map[string][]string, error) {ctx, cancel := context.WithTimeout(ctx, discoverLabelsTimeout)defer cancel()@@ -23,7 +23,7 @@ func (r *profileRepository) DiscoverLabels(ctx context.Context, projectId uuid.Uwg.Add(1)go func(key string) {defer wg.Done()- values, err := r.distinctLabelValues(ctx, projectId, service, profileType, key, from, to)+ values, err := distinct(ctx, key)mu.Lock()defer mu.Unlock()if err != nil {diff --git a/backend/app/repositories/telemetry/shared/session_filter.go b/backend/app/repositories/telemetry/shared/session_filter.gonew file mode 100644index 00000000..81a5eccf--- /dev/null+++ b/backend/app/repositories/telemetry/shared/session_filter.go@@ -0,0 +1,9 @@+package shared++// SessionAttributeFilter narrows the sessions list by an exact key=value+// match against the JSON `attributes` blob. Defined here so every telemetry+// backend sees the same type.+type SessionAttributeFilter struct {+ Key string+ Value string+}diff --git a/backend/app/repositories/telemetry/shared/sqlfilter.go b/backend/app/repositories/telemetry/shared/sqlfilter.gonew file mode 100644index 00000000..e6d40144--- /dev/null+++ b/backend/app/repositories/telemetry/shared/sqlfilter.go@@ -0,0 +1,27 @@+package shared++import "sort"++// RootFilterClause returns the WHERE fragment for the issues/endpoints+// root-vs-non-root filter; both embedded backends store is_root as 0/1.+func RootFilterClause(qualifiedCol, rootFilter string) string {+ switch rootFilter {+ case "root":+ return " AND " + qualifiedCol + " = 1"+ case "non_root":+ return " AND " + qualifiedCol + " = 0"+ default:+ return ""+ }+}++// SortedKeys returns map keys in stable order so generated SQL and its+// bound parameters line up deterministically.+func SortedKeys(m map[string]string) []string {+ keys := make([]string, 0, len(m))+ for k := range m {+ keys = append(keys, k)+ }+ sort.Strings(keys)+ return keys+}diff --git a/backend/app/repositories/trace_window.go b/backend/app/repositories/telemetry/shared/trace_window.gosimilarity index 68%rename from backend/app/repositories/trace_window.gorename to backend/app/repositories/telemetry/shared/trace_window.goindex 7d9fa538..7cce41fd 100644--- a/backend/app/repositories/trace_window.go+++ b/backend/app/repositories/telemetry/shared/trace_window.go@@ -1,4 +1,4 @@-package repositories+package sharedimport "time"@@ -6,10 +6,10 @@ const traceLookupWindow = 24 * time.Hourconst distributedTraceLookupWindow = 48 * time.Hour-func traceWindowBounds(recordedAt time.Time) (time.Time, time.Time) {+func TraceWindowBounds(recordedAt time.Time) (time.Time, time.Time) {return recordedAt.Add(-traceLookupWindow), recordedAt.Add(traceLookupWindow)}-func distributedTraceWindowBounds(recordedAt time.Time) (time.Time, time.Time) {+func DistributedTraceWindowBounds(recordedAt time.Time) (time.Time, time.Time) {return recordedAt.Add(-distributedTraceLookupWindow), recordedAt.Add(distributedTraceLookupWindow)}diff --git a/backend/app/repositories/telemetry/shared/types.go b/backend/app/repositories/telemetry/shared/types.gonew file mode 100644index 00000000..b69fa3aa--- /dev/null+++ b/backend/app/repositories/telemetry/shared/types.go@@ -0,0 +1,51 @@+package shared++import (+ "time"++ "github.com/google/uuid"+)++type FiredNotification struct {+ ProjectId uuid.UUID+ RuleId int+ RuleType string+ RuleName string+ ChannelType string+ ChannelName string+ Severity string+ Subject string+ Body string+ Status string+ ErrorMsg string+ Endpoint string+ URL string+ FiredAt time.Time+}++// LogAttributeFilter selects logs by an exact attribute value. Scope is one of+// "resource", "scope", or "log"; picks which of the three attribute maps to+// query (Map columns with bloom-filter indexes on ClickHouse, JSON on+// SQLite/DuckDB).+type LogAttributeFilter struct {+ Scope string+ Key string+ Value string+}++type LogSearchParams struct {+ ProjectId uuid.UUID+ FromDate time.Time+ ToDate time.Time+ Search string+ SearchType string+ MinSeverity uint8+ ServiceName string+ TraceId string+ TraceIds []string+ AttributeFilters []LogAttributeFilter+ OrderBy string+ SortDirection string+ Page int+ PageSize int+}diff --git a/backend/app/repositories/span_repository_test.go b/backend/app/repositories/telemetry/span_repository_test.gosimilarity index 99%rename from backend/app/repositories/span_repository_test.gorename to backend/app/repositories/telemetry/span_repository_test.goindex cc2d73bf..f804ff07 100644--- a/backend/app/repositories/span_repository_test.go+++ b/backend/app/repositories/telemetry/span_repository_test.go@@ -1,4 +1,4 @@-package repositories+package telemetryimport ("context"diff --git a/backend/app/repositories/ai_trace.repository_sqlite.go b/backend/app/repositories/telemetry/sqlite/ai_trace.repository.gosimilarity index 79%rename from backend/app/repositories/ai_trace.repository_sqlite.gorename to backend/app/repositories/telemetry/sqlite/ai_trace.repository.goindex 85323ea8..f1d62879 100644--- a/backend/app/repositories/ai_trace.repository_sqlite.go+++ b/backend/app/repositories/telemetry/sqlite/ai_trace.repository.go@@ -1,10 +1,12 @@-//go:build !pgch+//go:build !telemetry_ch && !telemetry_duckdb-package repositories+package sqliteimport ("context""fmt"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/shared"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/sqlitetypes""sort""strings""time"@@ -22,32 +24,32 @@ func (aiTraceRowNaming) GetTableNameFromStructName(string) string {}type aiTraceRow struct {- Id uuid.UUID `lit:"id"`- ProjectId uuid.UUID `lit:"project_id"`- RecordedAt SQLiteTime `lit:"recorded_at"`- Duration int64 `lit:"duration"`- StatusCode uint8 `lit:"status_code"`- Model string `lit:"model"`- ResponseModel string `lit:"response_model"`- Provider string `lit:"provider"`- Operation string `lit:"operation"`- InputTokens int64 `lit:"input_tokens"`- OutputTokens int64 `lit:"output_tokens"`- TotalTokens int64 `lit:"total_tokens"`- CachedTokens int64 `lit:"cached_tokens"`- ReasoningTokens int64 `lit:"reasoning_tokens"`- InputCost float64 `lit:"input_cost"`- OutputCost float64 `lit:"output_cost"`- TotalCost float64 `lit:"total_cost"`- TraceName string `lit:"trace_name"`- UserId string `lit:"user_id"`- FinishReason string `lit:"finish_reason"`- ServerName string `lit:"server_name"`- AppVersion string `lit:"app_version"`- StorageKey string `lit:"storage_key"`- Attributes SQLiteJSONMap `lit:"attributes"`- DistributedTraceId *uuid.UUID `lit:"distributed_trace_id"`- IsRoot bool `lit:"is_root"`+ Id uuid.UUID `lit:"id"`+ ProjectId uuid.UUID `lit:"project_id"`+ RecordedAt sqlitetypes.SQLiteTime `lit:"recorded_at"`+ Duration int64 `lit:"duration"`+ StatusCode uint8 `lit:"status_code"`+ Model string `lit:"model"`+ ResponseModel string `lit:"response_model"`+ Provider string `lit:"provider"`+ Operation string `lit:"operation"`+ InputTokens int64 `lit:"input_tokens"`+ OutputTokens int64 `lit:"output_tokens"`+ TotalTokens int64 `lit:"total_tokens"`+ CachedTokens int64 `lit:"cached_tokens"`+ ReasoningTokens int64 `lit:"reasoning_tokens"`+ InputCost float64 `lit:"input_cost"`+ OutputCost float64 `lit:"output_cost"`+ TotalCost float64 `lit:"total_cost"`+ TraceName string `lit:"trace_name"`+ UserId string `lit:"user_id"`+ FinishReason string `lit:"finish_reason"`+ ServerName string `lit:"server_name"`+ AppVersion string `lit:"app_version"`+ StorageKey string `lit:"storage_key"`+ Attributes sqlitetypes.SQLiteJSONMap `lit:"attributes"`+ DistributedTraceId *uuid.UUID `lit:"distributed_trace_id"`+ IsRoot bool `lit:"is_root"`}type groupedAiTraceRow struct {@@ -89,7 +91,7 @@ func aiTraceToRow(t models.AiTrace) aiTraceRow {return aiTraceRow{Id: t.Id,ProjectId: t.ProjectId,- RecordedAt: NewSQLiteTime(t.RecordedAt),+ RecordedAt: sqlitetypes.NewSQLiteTime(t.RecordedAt),Duration: int64(t.Duration),StatusCode: t.StatusCode,Model: t.Model,@@ -110,7 +112,7 @@ func aiTraceToRow(t models.AiTrace) aiTraceRow {ServerName: t.ServerName,AppVersion: t.AppVersion,StorageKey: t.StorageKey,- Attributes: NewSQLiteJSONMap(t.Attributes),+ Attributes: sqlitetypes.NewSQLiteJSONMap(t.Attributes),DistributedTraceId: t.DistributedTraceId,IsRoot: t.IsRoot,}@@ -173,14 +175,14 @@ func (r *aiTraceRepository) InsertAsync(ctx context.Context, lines []models.AiTr}func (r *aiTraceRepository) FindGroupedByTraceName(ctx context.Context, projectId uuid.UUID, fromDate, toDate time.Time, page, pageSize int, orderBy, sortDirection, search, rootFilter string) ([]models.AiTraceStats, int64, error) {- params := lit.P{"project_id": projectId, "from": NewSQLiteTime(fromDate), "to": NewSQLiteTime(toDate)}+ params := lit.P{"project_id": projectId, "from": sqlitetypes.NewSQLiteTime(fromDate), "to": sqlitetypes.NewSQLiteTime(toDate)}whereClause := "project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to"if search != "" {whereClause += " AND INSTR(LOWER(trace_name), LOWER(:search)) > 0"params["search"] = search}- whereClause += rootFilterClause("is_root", rootFilter)+ whereClause += shared.RootFilterClause("is_root", rootFilter)countResult, err := lit.SelectSingleNamed[models.CountResult](db.TelemetryDB,"SELECT COUNT(DISTINCT trace_name) AS count FROM ai_traces WHERE "+whereClause, params)@@ -211,7 +213,7 @@ func (r *aiTraceRepository) FindGroupedByTraceName(ctx context.Context, projectIvar stats []models.AiTraceStatsfor _, row := range rows {// Compute percentiles from raw durations for this trace_name- durationParams := lit.P{"project_id": projectId, "from": NewSQLiteTime(fromDate), "to": NewSQLiteTime(toDate), "trace_name": row.TraceName}+ durationParams := lit.P{"project_id": projectId, "from": sqlitetypes.NewSQLiteTime(fromDate), "to": sqlitetypes.NewSQLiteTime(toDate), "trace_name": row.TraceName}durationRows, err := lit.SelectNamed[aiTraceDurationRow](db.TelemetryDB,`SELECT CAST(duration AS REAL) AS duration FROM ai_tracesWHERE project_id = :project_id AND trace_name = :trace_name AND recorded_at >= :from AND recorded_at <= :to@@ -230,8 +232,8 @@ func (r *aiTraceRepository) FindGroupedByTraceName(ctx context.Context, projectIstats = append(stats, models.AiTraceStats{TraceName: row.TraceName,Count: row.TotalCount,- P50Duration: time.Duration(computePercentile(sortedDurations, 0.5)),- P95Duration: time.Duration(computePercentile(sortedDurations, 0.95)),+ P50Duration: time.Duration(shared.ComputePercentile(sortedDurations, 0.5)),+ P95Duration: time.Duration(shared.ComputePercentile(sortedDurations, 0.95)),AvgDuration: time.Duration(row.AvgDuration),TotalTokens: row.TotalTokens,TotalCost: row.TotalCost,@@ -280,7 +282,7 @@ func (r *aiTraceRepository) FindGroupedByTraceName(ctx context.Context, projectI}func (r *aiTraceRepository) FindByTraceName(ctx context.Context, projectId uuid.UUID, traceName string, fromDate, toDate time.Time, page, pageSize int, orderBy, sortDirection string) ([]models.AiTrace, int64, error) {- params := lit.P{"project_id": projectId, "trace_name": traceName, "from": NewSQLiteTime(fromDate), "to": NewSQLiteTime(toDate)}+ params := lit.P{"project_id": projectId, "trace_name": traceName, "from": sqlitetypes.NewSQLiteTime(fromDate), "to": sqlitetypes.NewSQLiteTime(toDate)}countResult, err := lit.SelectSingleNamed[models.CountResult](db.TelemetryDB,"SELECT COUNT(*) AS count FROM ai_traces WHERE project_id = :project_id AND trace_name = :trace_name AND recorded_at >= :from AND recorded_at <= :to",@@ -317,7 +319,7 @@ func (r *aiTraceRepository) FindByTraceName(ctx context.Context, projectId uuid.FROM ai_tracesWHERE project_id = :project_id AND trace_name = :trace_name AND recorded_at >= :from AND recorded_at <= :toORDER BY %s %s LIMIT :limit OFFSET :offset`, orderBy, sortDir),- lit.P{"project_id": projectId, "trace_name": traceName, "from": NewSQLiteTime(fromDate), "to": NewSQLiteTime(toDate), "limit": pageSize, "offset": offset})+ lit.P{"project_id": projectId, "trace_name": traceName, "from": sqlitetypes.NewSQLiteTime(fromDate), "to": sqlitetypes.NewSQLiteTime(toDate), "limit": pageSize, "offset": offset})if err != nil {return nil, 0, err}@@ -336,15 +338,15 @@ func (r *aiTraceRepository) GetTraceNameStats(ctx context.Context, projectId uuidurationMinutes = 1}- params := lit.P{"project_id": projectId, "trace_name": traceName, "from": NewSQLiteTime(start), "to": NewSQLiteTime(end)}+ params := lit.P{"project_id": projectId, "trace_name": traceName, "from": sqlitetypes.NewSQLiteTime(start), "to": sqlitetypes.NewSQLiteTime(end)}row, err := lit.SelectSingleNamed[aiTraceDetailStatsRow](db.TelemetryDB,`SELECT COUNT(*) AS count,CASE WHEN COUNT(*) > 0 THEN AVG(duration) / 1000000.0 ELSE 0 END AS avg_duration_ms,- SUM(total_tokens) AS total_tokens,- SUM(total_cost) AS total_cost,- AVG(input_tokens) AS avg_input_tokens,- AVG(output_tokens) AS avg_output_tokens+ COALESCE(SUM(total_tokens), 0) AS total_tokens,+ COALESCE(SUM(total_cost), 0) AS total_cost,+ COALESCE(AVG(input_tokens), 0) AS avg_input_tokens,+ COALESCE(AVG(output_tokens), 0) AS avg_output_tokensFROM ai_tracesWHERE project_id = :project_id AND trace_name = :trace_name AND recorded_at >= :from AND recorded_at <= :to`,params)@@ -376,8 +378,8 @@ func (r *aiTraceRepository) GetTraceNameStats(ctx context.Context, projectId uuifor i, d := range durationRows {sortedDurations[i] = d.Duration}- stats.MedianDuration = computePercentile(sortedDurations, 0.5)- stats.P95Duration = computePercentile(sortedDurations, 0.95)+ stats.MedianDuration = shared.ComputePercentile(sortedDurations, 0.5)+ stats.P95Duration = shared.ComputePercentile(sortedDurations, 0.95)return stats, nil}@@ -393,10 +395,10 @@ func (r *aiTraceRepository) FindById(ctx context.Context, projectId, traceId uuiWHERE project_id = :project_id AND id = :id`params := lit.P{"project_id": projectId, "id": traceId}if recordedAt != nil {- from, to := traceWindowBounds(*recordedAt)+ from, to := shared.TraceWindowBounds(*recordedAt)query += ` AND recorded_at >= :from AND recorded_at <= :to`- params["from"] = NewSQLiteTime(from)- params["to"] = NewSQLiteTime(to)+ params["from"] = sqlitetypes.NewSQLiteTime(from)+ params["to"] = sqlitetypes.NewSQLiteTime(to)}query += ` LIMIT 1`@@ -430,10 +432,10 @@ func (r *aiTraceRepository) FindByDistributedTraceId(ctx context.Context, distristorage_key, attributes, distributed_trace_id, is_rootFROM ai_traces WHERE distributed_trace_id = :trace_id AND project_id IN (` + strings.Join(placeholders, ",") + `)`if recordedAt != nil {- from, to := distributedTraceWindowBounds(*recordedAt)+ from, to := shared.DistributedTraceWindowBounds(*recordedAt)query += ` AND recorded_at >= :from AND recorded_at <= :to`- params["from"] = NewSQLiteTime(from)- params["to"] = NewSQLiteTime(to)+ params["from"] = sqlitetypes.NewSQLiteTime(from)+ params["to"] = sqlitetypes.NewSQLiteTime(to)}query += ` ORDER BY recorded_at ASC`@@ -465,4 +467,4 @@ func (r *aiTraceRepository) FindByDistributedTraceId(ctx context.Context, distrireturn traces, nil}-var AiTraceRepository = aiTraceRepository{}+var AiTraceRepository = &aiTraceRepository{}diff --git a/backend/app/repositories/endpoint.repository_sqlite.go b/backend/app/repositories/telemetry/sqlite/endpoint.repository.gosimilarity index 80%rename from backend/app/repositories/endpoint.repository_sqlite.gorename to backend/app/repositories/telemetry/sqlite/endpoint.repository.goindex fd2cd1c1..4e1e34f2 100644--- a/backend/app/repositories/endpoint.repository_sqlite.go+++ b/backend/app/repositories/telemetry/sqlite/endpoint.repository.go@@ -1,12 +1,13 @@-//go:build !pgch+//go:build !telemetry_ch && !telemetry_duckdb-package repositories+package sqliteimport ("context""database/sql""fmt"- "math"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/shared"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/sqlitetypes""sort""strings""time"@@ -18,21 +19,21 @@ import ()type endpoint struct {- Id uuid.UUID `lit:"id"`- ProjectId uuid.UUID `lit:"project_id"`- Endpoint string `lit:"endpoint"`- Duration int64 `lit:"duration"`- RecordedAt SQLiteTime `lit:"recorded_at"`- StatusCode int16 `lit:"status_code"`- BodySize int32 `lit:"body_size"`- ClientIP string `lit:"client_ip"`- Attributes SQLiteJSONMap `lit:"attributes"`- AppVersion string `lit:"app_version"`- ServerName string `lit:"server_name"`- DistributedTraceId *uuid.UUID `lit:"distributed_trace_id"`- SpanId *uuid.UUID `lit:"span_id"`- IsStream bool `lit:"is_stream"`- IsRoot bool `lit:"is_root"`+ Id uuid.UUID `lit:"id"`+ ProjectId uuid.UUID `lit:"project_id"`+ Endpoint string `lit:"endpoint"`+ Duration int64 `lit:"duration"`+ RecordedAt sqlitetypes.SQLiteTime `lit:"recorded_at"`+ StatusCode int16 `lit:"status_code"`+ BodySize int32 `lit:"body_size"`+ ClientIP string `lit:"client_ip"`+ Attributes sqlitetypes.SQLiteJSONMap `lit:"attributes"`+ AppVersion string `lit:"app_version"`+ ServerName string `lit:"server_name"`+ DistributedTraceId *uuid.UUID `lit:"distributed_trace_id"`+ SpanId *uuid.UUID `lit:"span_id"`+ IsStream bool `lit:"is_stream"`+ IsRoot bool `lit:"is_root"`}type groupedEndpointRow struct {@@ -99,11 +100,11 @@ func endpointToRow(e models.Endpoint) endpoint {ProjectId: e.ProjectId,Endpoint: e.Endpoint,Duration: int64(e.Duration),- RecordedAt: NewSQLiteTime(e.RecordedAt),+ RecordedAt: sqlitetypes.NewSQLiteTime(e.RecordedAt),StatusCode: e.StatusCode,BodySize: e.BodySize,ClientIP: e.ClientIP,- Attributes: NewSQLiteJSONMap(e.Attributes),+ Attributes: sqlitetypes.NewSQLiteJSONMap(e.Attributes),AppVersion: e.AppVersion,ServerName: e.ServerName,DistributedTraceId: e.DistributedTraceId,@@ -139,17 +140,6 @@ func (r *endpoint) toModel() models.Endpoint {// rootFilterClause returns a SQL fragment ("", " AND <col> = 1", " AND <col> = 0")// to splice into a WHERE clause based on the rootFilter param. Accepts "all" |// "root" | "non_root"; defaults to "all" (no filter).-func rootFilterClause(qualifiedCol, rootFilter string) string {- switch rootFilter {- case "root":- return " AND " + qualifiedCol + " = 1"- case "non_root":- return " AND " + qualifiedCol + " = 0"- default:- return ""- }-}-type endpointRepository struct{}func (e *endpointRepository) InsertAsync(ctx context.Context, lines []models.Endpoint) error {@@ -176,7 +166,7 @@ func (e *endpointRepository) InsertAsync(ctx context.Context, lines []models.Endfunc (e *endpointRepository) CountBetween(ctx context.Context, projectId uuid.UUID, start, end time.Time) (int64, error) {result, err := lit.SelectSingleNamed[models.CountResult](db.TelemetryDB,"SELECT COUNT(*) AS count FROM endpoints WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to",- lit.P{"project_id": projectId, "from": NewSQLiteTime(start), "to": NewSQLiteTime(end)})+ lit.P{"project_id": projectId, "from": sqlitetypes.NewSQLiteTime(start), "to": sqlitetypes.NewSQLiteTime(end)})if err != nil {return 0, err}@@ -187,7 +177,7 @@ func (e *endpointRepository) CountBetween(ctx context.Context, projectId uuid.UU}func (e *endpointRepository) FindAll(ctx context.Context, projectId uuid.UUID, fromDate, toDate time.Time, page, pageSize int, orderBy string) ([]models.Endpoint, int64, error) {- params := lit.P{"project_id": projectId, "from": NewSQLiteTime(fromDate), "to": NewSQLiteTime(toDate)}+ params := lit.P{"project_id": projectId, "from": sqlitetypes.NewSQLiteTime(fromDate), "to": sqlitetypes.NewSQLiteTime(toDate)}countResult, err := lit.SelectSingleNamed[models.CountResult](db.TelemetryDB,"SELECT COUNT(*) AS count FROM endpoints WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to",@@ -211,7 +201,7 @@ func (e *endpointRepository) FindAll(ctx context.Context, projectId uuid.UUID, ffmt.Sprintf(`SELECT id, project_id, endpoint, duration, recorded_at, status_code, body_size, client_ip, attributes, app_version, server_name, distributed_trace_idFROM endpoints WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :toORDER BY %s DESC LIMIT :limit OFFSET :offset`, orderBy),- lit.P{"project_id": projectId, "from": NewSQLiteTime(fromDate), "to": NewSQLiteTime(toDate), "limit": pageSize, "offset": offset})+ lit.P{"project_id": projectId, "from": sqlitetypes.NewSQLiteTime(fromDate), "to": sqlitetypes.NewSQLiteTime(toDate), "limit": pageSize, "offset": offset})if err != nil {return nil, 0, err}@@ -225,14 +215,14 @@ func (e *endpointRepository) FindAll(ctx context.Context, projectId uuid.UUID, f}func (e *endpointRepository) FindGroupedByEndpoint(ctx context.Context, projectId uuid.UUID, fromDate, toDate time.Time, page, pageSize int, orderBy string, sortDirection string, search string, rootFilter string) ([]models.EndpointStats, int64, error) {- params := lit.P{"project_id": projectId, "from": NewSQLiteTime(fromDate), "to": NewSQLiteTime(toDate)}+ params := lit.P{"project_id": projectId, "from": sqlitetypes.NewSQLiteTime(fromDate), "to": sqlitetypes.NewSQLiteTime(toDate)}whereClause := "e.project_id = :project_id AND e.recorded_at >= :from AND e.recorded_at <= :to"if search != "" {whereClause += " AND INSTR(LOWER(e.endpoint), LOWER(:search)) > 0"params["search"] = search}- whereClause += rootFilterClause("e.is_root", rootFilter)+ whereClause += shared.RootFilterClause("e.is_root", rootFilter)countQuery := "SELECT COUNT(DISTINCT e.endpoint) AS count FROM endpoints e WHERE " + whereClausetotalResult, err := lit.SelectSingleNamed[models.CountResult](db.TelemetryDB, countQuery, params)@@ -299,8 +289,8 @@ func (e *endpointRepository) FindGroupedByEndpoint(ctx context.Context, projectIEndpoint: g.Endpoint,Count: g.TotalCount,LastSeen: lastSeen,- Impact: ComputeStreamImpact(g.Endpoint, g.TotalCount, g.ServerErrorCount, g.ClientErrorCount),- ImpactReason: ComputeStreamImpactReason(g.Endpoint, g.TotalCount, g.ServerErrorCount, g.ClientErrorCount),+ Impact: shared.ComputeStreamImpact(g.Endpoint, g.TotalCount, g.ServerErrorCount, g.ClientErrorCount),+ ImpactReason: shared.ComputeStreamImpactReason(g.Endpoint, g.TotalCount, g.ServerErrorCount, g.ClientErrorCount),IsStream: true,HasRoot: g.HasRoot,HasNonRoot: g.HasNonRoot,@@ -313,11 +303,11 @@ func (e *endpointRepository) FindGroupedByEndpoint(ctx context.Context, projectIreturn nil, 0, err}- p50 := computePercentile(durations, 0.5)- p95 := computePercentile(durations, 0.95)- p99 := computePercentile(durations, 0.99)+ p50 := shared.ComputePercentile(durations, 0.5)+ p95 := shared.ComputePercentile(durations, 0.95)+ p99 := shared.ComputePercentile(durations, 0.99)- impact := ComputeImpactScore(g.Endpoint, g.TotalCount, g.SatisfiedCount, g.ToleratingCount, g.BadCount, g.ClientErrorCount, p99, g.OffsetMs)+ impact := shared.ComputeImpactScore(g.Endpoint, g.TotalCount, g.SatisfiedCount, g.ToleratingCount, g.BadCount, g.ClientErrorCount, p99, g.OffsetMs)stats = append(stats, models.EndpointStats{Endpoint: g.Endpoint,@@ -328,7 +318,7 @@ func (e *endpointRepository) FindGroupedByEndpoint(ctx context.Context, projectIAvgDuration: time.Duration(g.AvgDuration),LastSeen: lastSeen,Impact: impact,- ImpactReason: ComputeImpactReason(g.Endpoint, g.TotalCount, g.SatisfiedCount, g.ToleratingCount,+ ImpactReason: shared.ComputeImpactReason(g.Endpoint, g.TotalCount, g.SatisfiedCount, g.ToleratingCount,g.BadCount, g.ClientErrorCount, p99, g.OffsetMs),HasRoot: g.HasRoot,HasNonRoot: g.HasNonRoot,@@ -350,7 +340,7 @@ func (e *endpointRepository) FindGroupedByEndpoint(ctx context.Context, projectI}func (e *endpointRepository) FindByEndpoint(ctx context.Context, projectId uuid.UUID, endpointName string, fromDate, toDate time.Time, page, pageSize int, orderBy string, sortDirection string) ([]models.Endpoint, int64, error) {- params := lit.P{"project_id": projectId, "endpoint": endpointName, "from": NewSQLiteTime(fromDate), "to": NewSQLiteTime(toDate)}+ params := lit.P{"project_id": projectId, "endpoint": endpointName, "from": sqlitetypes.NewSQLiteTime(fromDate), "to": sqlitetypes.NewSQLiteTime(toDate)}countResult, err := lit.SelectSingleNamed[models.CountResult](db.TelemetryDB,"SELECT COUNT(*) AS count FROM endpoints WHERE project_id = :project_id AND endpoint = :endpoint AND recorded_at >= :from AND recorded_at <= :to",@@ -379,7 +369,7 @@ func (e *endpointRepository) FindByEndpoint(ctx context.Context, projectId uuid.fmt.Sprintf(`SELECT id, project_id, endpoint, duration, recorded_at, status_code, body_size, client_ip, attributes, app_version, server_name, distributed_trace_idFROM endpoints WHERE project_id = :project_id AND endpoint = :endpoint AND recorded_at >= :from AND recorded_at <= :toORDER BY %s %s LIMIT :limit OFFSET :offset`, orderBy, sortDir),- lit.P{"project_id": projectId, "endpoint": endpointName, "from": NewSQLiteTime(fromDate), "to": NewSQLiteTime(toDate), "limit": pageSize, "offset": offset})+ lit.P{"project_id": projectId, "endpoint": endpointName, "from": sqlitetypes.NewSQLiteTime(fromDate), "to": sqlitetypes.NewSQLiteTime(toDate), "limit": pageSize, "offset": offset})if err != nil {return nil, 0, err}@@ -397,10 +387,10 @@ func (e *endpointRepository) FindById(ctx context.Context, projectId, endpointIdFROM endpoints WHERE project_id = :project_id AND id = :id`params := lit.P{"project_id": projectId, "id": endpointId}if recordedAt != nil {- from, to := traceWindowBounds(*recordedAt)+ from, to := shared.TraceWindowBounds(*recordedAt)query += ` AND recorded_at >= :from AND recorded_at <= :to`- params["from"] = NewSQLiteTime(from)- params["to"] = NewSQLiteTime(to)+ params["from"] = sqlitetypes.NewSQLiteTime(from)+ params["to"] = sqlitetypes.NewSQLiteTime(to)}query += ` LIMIT 1`@@ -416,84 +406,84 @@ func (e *endpointRepository) FindById(ctx context.Context, projectId, endpointId}func (e *endpointRepository) CountByHour(ctx context.Context, projectId uuid.UUID, start, end time.Time) ([]models.TimeSeriesPoint, error) {- results, err := lit.SelectNamed[timeSeriesResult](db.TelemetryDB,+ results, err := lit.SelectNamed[sqlitetypes.TimeSeriesResult](db.TelemetryDB,`SELECT strftime('%Y-%m-%d %H:00:00', recorded_at) as bucket, CAST(COUNT(*) AS REAL) as agg_valueFROM endpoints WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :toGROUP BY bucket ORDER BY bucket ASC`,- lit.P{"project_id": projectId, "from": NewSQLiteTime(start), "to": NewSQLiteTime(end)})+ lit.P{"project_id": projectId, "from": sqlitetypes.NewSQLiteTime(start), "to": sqlitetypes.NewSQLiteTime(end)})if err != nil {return nil, err}- return timeSeriesResultsToPoints(results), nil+ return sqlitetypes.TimeSeriesResultsToPoints(results), nil}func (e *endpointRepository) AvgDurationByHour(ctx context.Context, projectId uuid.UUID, start, end time.Time) ([]models.TimeSeriesPoint, error) {- results, err := lit.SelectNamed[timeSeriesResult](db.TelemetryDB,+ results, err := lit.SelectNamed[sqlitetypes.TimeSeriesResult](db.TelemetryDB,`SELECT strftime('%Y-%m-%d %H:00:00', recorded_at) as bucket, AVG(duration) / 1000000.0 as agg_valueFROM endpoints WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to AND is_stream = 0GROUP BY bucket ORDER BY bucket ASC`,- lit.P{"project_id": projectId, "from": NewSQLiteTime(start), "to": NewSQLiteTime(end)})+ lit.P{"project_id": projectId, "from": sqlitetypes.NewSQLiteTime(start), "to": sqlitetypes.NewSQLiteTime(end)})if err != nil {return nil, err}- return timeSeriesResultsToPoints(results), nil+ return sqlitetypes.TimeSeriesResultsToPoints(results), nil}func (e *endpointRepository) ErrorRateByHour(ctx context.Context, projectId uuid.UUID, start, end time.Time) ([]models.TimeSeriesPoint, error) {- results, err := lit.SelectNamed[timeSeriesResult](db.TelemetryDB,+ results, err := lit.SelectNamed[sqlitetypes.TimeSeriesResult](db.TelemetryDB,`SELECT strftime('%Y-%m-%d %H:00:00', recorded_at) as bucket,SUM(CASE WHEN status_code >= 500 THEN 1 ELSE 0 END) * 100.0 / COUNT(*) as agg_valueFROM endpoints WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :toGROUP BY bucket ORDER BY bucket ASC`,- lit.P{"project_id": projectId, "from": NewSQLiteTime(start), "to": NewSQLiteTime(end)})+ lit.P{"project_id": projectId, "from": sqlitetypes.NewSQLiteTime(start), "to": sqlitetypes.NewSQLiteTime(end)})if err != nil {return nil, err}- return timeSeriesResultsToPoints(results), nil+ return sqlitetypes.TimeSeriesResultsToPoints(results), nil}func (e *endpointRepository) CountByInterval(ctx context.Context, projectId uuid.UUID, start, end time.Time, intervalMinutes int) ([]models.TimeSeriesPoint, error) {secs := intervalMinutes * 60- results, err := lit.SelectNamed[timeSeriesResult](db.TelemetryDB,+ results, err := lit.SelectNamed[sqlitetypes.TimeSeriesResult](db.TelemetryDB,fmt.Sprintf(`SELECT datetime((strftime('%%s', recorded_at) / %d) * %d, 'unixepoch') as bucket, CAST(COUNT(*) AS REAL) as agg_valueFROM endpoints WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :toGROUP BY bucket ORDER BY bucket ASC`, secs, secs),- lit.P{"project_id": projectId, "from": NewSQLiteTime(start), "to": NewSQLiteTime(end)})+ lit.P{"project_id": projectId, "from": sqlitetypes.NewSQLiteTime(start), "to": sqlitetypes.NewSQLiteTime(end)})if err != nil {return nil, err}- return timeSeriesResultsToPoints(results), nil+ return sqlitetypes.TimeSeriesResultsToPoints(results), nil}func (e *endpointRepository) AvgDurationByInterval(ctx context.Context, projectId uuid.UUID, start, end time.Time, intervalMinutes int) ([]models.TimeSeriesPoint, error) {secs := intervalMinutes * 60- results, err := lit.SelectNamed[timeSeriesResult](db.TelemetryDB,+ results, err := lit.SelectNamed[sqlitetypes.TimeSeriesResult](db.TelemetryDB,fmt.Sprintf(`SELECT datetime((strftime('%%s', recorded_at) / %d) * %d, 'unixepoch') as bucket, AVG(duration) / 1000000.0 as agg_valueFROM endpoints WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to AND is_stream = 0GROUP BY bucket ORDER BY bucket ASC`, secs, secs),- lit.P{"project_id": projectId, "from": NewSQLiteTime(start), "to": NewSQLiteTime(end)})+ lit.P{"project_id": projectId, "from": sqlitetypes.NewSQLiteTime(start), "to": sqlitetypes.NewSQLiteTime(end)})if err != nil {return nil, err}- return timeSeriesResultsToPoints(results), nil+ return sqlitetypes.TimeSeriesResultsToPoints(results), nil}func (e *endpointRepository) ErrorRateByInterval(ctx context.Context, projectId uuid.UUID, start, end time.Time, intervalMinutes int) ([]models.TimeSeriesPoint, error) {secs := intervalMinutes * 60- results, err := lit.SelectNamed[timeSeriesResult](db.TelemetryDB,+ results, err := lit.SelectNamed[sqlitetypes.TimeSeriesResult](db.TelemetryDB,fmt.Sprintf(`SELECT datetime((strftime('%%s', recorded_at) / %d) * %d, 'unixepoch') as bucket,SUM(CASE WHEN status_code >= 500 THEN 1 ELSE 0 END) * 100.0 / COUNT(*) as agg_valueFROM endpoints WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :toGROUP BY bucket ORDER BY bucket ASC`, secs, secs),- lit.P{"project_id": projectId, "from": NewSQLiteTime(start), "to": NewSQLiteTime(end)})+ lit.P{"project_id": projectId, "from": sqlitetypes.NewSQLiteTime(start), "to": sqlitetypes.NewSQLiteTime(end)})if err != nil {return nil, err}- return timeSeriesResultsToPoints(results), nil+ return sqlitetypes.TimeSeriesResultsToPoints(results), nil}func (e *endpointRepository) FindWorstEndpoints(ctx context.Context, projectId uuid.UUID, start, end time.Time, limit int) ([]models.EndpointStats, error) {- params := lit.P{"project_id": projectId, "from": NewSQLiteTime(start), "to": NewSQLiteTime(end)}+ params := lit.P{"project_id": projectId, "from": sqlitetypes.NewSQLiteTime(start), "to": sqlitetypes.NewSQLiteTime(end)}groupQuery := `SELECTe.endpoint,@@ -541,11 +531,11 @@ func (e *endpointRepository) FindWorstEndpoints(ctx context.Context, projectId ureturn nil, err}- p50 := computePercentile(durations, 0.5)- p95 := computePercentile(durations, 0.95)- p99 := computePercentile(durations, 0.99)+ p50 := shared.ComputePercentile(durations, 0.5)+ p95 := shared.ComputePercentile(durations, 0.95)+ p99 := shared.ComputePercentile(durations, 0.99)- impact := ComputeImpactScore(g.Endpoint, g.TotalCount, g.SatisfiedCount, g.ToleratingCount, g.BadCount, g.ClientErrorCount, p99, g.OffsetMs)+ impact := shared.ComputeImpactScore(g.Endpoint, g.TotalCount, g.SatisfiedCount, g.ToleratingCount, g.BadCount, g.ClientErrorCount, p99, g.OffsetMs)lastSeen, _ := time.Parse(time.RFC3339Nano, g.LastSeen)@@ -558,7 +548,7 @@ func (e *endpointRepository) FindWorstEndpoints(ctx context.Context, projectId uAvgDuration: time.Duration(g.AvgDuration),LastSeen: lastSeen,Impact: impact,- ImpactReason: ComputeImpactReason(g.Endpoint, g.TotalCount, g.SatisfiedCount, g.ToleratingCount,+ ImpactReason: shared.ComputeImpactReason(g.Endpoint, g.TotalCount, g.SatisfiedCount, g.ToleratingCount,g.BadCount, g.ClientErrorCount, p99, g.OffsetMs),})}@@ -575,7 +565,7 @@ func (e *endpointRepository) FindWorstEndpoints(ctx context.Context, projectId u}func (e *endpointRepository) GetEndpointStats(ctx context.Context, projectId uuid.UUID, endpoint string, start, end time.Time) (*models.EndpointDetailStats, error) {- params := lit.P{"project_id": projectId, "endpoint": endpoint, "from": NewSQLiteTime(start), "to": NewSQLiteTime(end)}+ params := lit.P{"project_id": projectId, "endpoint": endpoint, "from": sqlitetypes.NewSQLiteTime(start), "to": sqlitetypes.NewSQLiteTime(end)}durationMinutes := end.Sub(start).Minutes()if durationMinutes < 1 {@@ -587,8 +577,8 @@ func (e *endpointRepository) GetEndpointStats(ctx context.Context, projectId uuiCOUNT(*) as count,CASE WHEN COUNT(*) > 0 THEN AVG(duration) / 1000000.0 ELSE 0 END as avg_duration_ms,CASE WHEN COUNT(*) > 0 THEN SUM(CASE WHEN status_code >= 500 THEN 1 ELSE 0 END) * 100.0 / COUNT(*) ELSE 0 END as error_rate,- SUM(CASE WHEN duration <= 500000000 AND status_code < 500 THEN 1 ELSE 0 END) +- SUM(CASE WHEN duration > 500000000 AND duration <= 2000000000 AND status_code < 500 THEN 1 ELSE 0 END) * 0.5 as satisfied_tolerating+ COALESCE(SUM(CASE WHEN duration <= 500000000 AND status_code < 500 THEN 1 ELSE 0 END) ++ SUM(CASE WHEN duration > 500000000 AND duration <= 2000000000 AND status_code < 500 THEN 1 ELSE 0 END) * 0.5, 0) as satisfied_toleratingFROM endpoints WHERE project_id = :project_id AND endpoint = :endpoint AND recorded_at >= :from AND recorded_at <= :to`,params)if err != nil {@@ -599,7 +589,7 @@ func (e *endpointRepository) GetEndpointStats(ctx context.Context, projectId uui}isStreamRow, err := lit.SelectSingleNamed[isStreamFlagRow](db.TelemetryDB,- `SELECT MAX(is_stream) as is_stream FROM endpoints WHERE project_id = :project_id AND endpoint = :endpoint AND recorded_at >= :from AND recorded_at <= :to`,+ `SELECT COALESCE(MAX(is_stream), 0) as is_stream FROM endpoints WHERE project_id = :project_id AND endpoint = :endpoint AND recorded_at >= :from AND recorded_at <= :to`,params)if err != nil {return nil, err@@ -624,9 +614,9 @@ func (e *endpointRepository) GetEndpointStats(ctx context.Context, projectId uui}if len(durations) > 0 {- stats.MedianDuration = computePercentile(durations, 0.5) / 1000000.0- stats.P95Duration = computePercentile(durations, 0.95) / 1000000.0- stats.P99Duration = computePercentile(durations, 0.99) / 1000000.0+ stats.MedianDuration = shared.ComputePercentile(durations, 0.5) / 1000000.0+ stats.P95Duration = shared.ComputePercentile(durations, 0.95) / 1000000.0+ stats.P99Duration = shared.ComputePercentile(durations, 0.99) / 1000000.0}}@@ -634,7 +624,7 @@ func (e *endpointRepository) GetEndpointStats(ctx context.Context, projectId uui}func (e *endpointRepository) GetEndpointStackedChart(ctx context.Context, projectId uuid.UUID, start, end time.Time, intervalMinutes int, metricType string) (*models.EndpointStackedChartResponse, error) {- params := lit.P{"project_id": projectId, "from": NewSQLiteTime(start), "to": NewSQLiteTime(end)}+ params := lit.P{"project_id": projectId, "from": sqlitetypes.NewSQLiteTime(start), "to": sqlitetypes.NewSQLiteTime(end)}topEndpoints, err := getTopEndpointsByMetric(ctx, projectId, start, end, metricType)if err != nil {@@ -741,7 +731,7 @@ func (e *endpointRepository) getStackedChartWithPercentiles(ctx context.Context,ORDER BY bucket ASC, endpoint ASC, duration ASC`, bucketSecs, bucketSecs)parsedQuery, args, err := lit.ParseNamedQuery(db.Driver, query,- lit.P{"project_id": projectId, "from": NewSQLiteTime(start), "to": NewSQLiteTime(end)})+ lit.P{"project_id": projectId, "from": sqlitetypes.NewSQLiteTime(start), "to": sqlitetypes.NewSQLiteTime(end)})if err != nil {return nil, err}@@ -777,7 +767,7 @@ func (e *endpointRepository) getStackedChartWithPercentiles(ctx context.Context,var series []models.EndpointTimeSeriesPointfor key, durations := range durationMap {sort.Float64s(durations)- val := computePercentile(durations, percentile) / 1000000.0+ val := shared.ComputePercentile(durations, percentile) / 1000000.0ts, _ := time.Parse("2006-01-02 15:04:05", key.bucket)series = append(series, models.EndpointTimeSeriesPoint{@@ -840,7 +830,7 @@ func (e *endpointRepository) UpsertSlowEndpoint(ctx context.Context, projectId ufunc fetchSortedDurations(ctx context.Context, projectId uuid.UUID, endpoint string, from, to time.Time) ([]float64, error) {results, err := lit.SelectNamed[endpointDurationRow](db.TelemetryDB,"SELECT duration FROM endpoints WHERE project_id = :project_id AND endpoint = :endpoint AND recorded_at >= :from AND recorded_at <= :to AND is_stream = 0 ORDER BY duration ASC",- lit.P{"project_id": projectId, "endpoint": endpoint, "from": NewSQLiteTime(from), "to": NewSQLiteTime(to)})+ lit.P{"project_id": projectId, "endpoint": endpoint, "from": sqlitetypes.NewSQLiteTime(from), "to": sqlitetypes.NewSQLiteTime(to)})if err != nil {return nil, err}@@ -851,74 +841,6 @@ func fetchSortedDurations(ctx context.Context, projectId uuid.UUID, endpoint strreturn durations, nil}-func ComputeImpactScore(endpoint string, total, satisfiedCount, toleratingCount, badCount, clientErrorCount uint64, p99Ns float64, offsetMs uint32) float64 {- if total == 0 {- return 0- }-- totalF := float64(total)- badF := float64(badCount)- clientF := float64(clientErrorCount)- offsetNs := float64(offsetMs) * 1_000_000-- apdexScore := 1.0 - (float64(satisfiedCount)+float64(toleratingCount)*0.5)/totalF-- badRate := badF / totalF- var errorRateScore float64- switch {- case badRate > 0.33:- errorRateScore = 0.75- case badRate > 0.20:- errorRateScore = 0.50- case badRate > 0.10:- errorRateScore = 0.25- }-- adjustedP99 := p99Ns - offsetNs- var p99Score float64- switch {- case adjustedP99 > 8_000_000_000:- p99Score = 0.75- case adjustedP99 > 6_000_000_000:- p99Score = 0.50- case adjustedP99 > 3_000_000_000:- p99Score = 0.25- }-- var clientErrorScore float64- if endpoint != "UNMATCHED" && total > 10 {- clientRate := clientF / totalF- switch {- case clientRate > 0.50:- clientErrorScore = 0.75- case clientRate > 0.25:- clientErrorScore = 0.50- }- }-- var volumeScore float64- switch {- case badRate > 0.10 && badCount >= 500:- volumeScore = 0.75- case badRate > 0.10 && badCount >= 50:- volumeScore = 0.50- case badRate > 0.05 && badCount >= 2000:- volumeScore = 0.75- case badRate > 0.05 && badCount >= 500:- volumeScore = 0.50- case badRate > 0.05 && badCount >= 50:- volumeScore = 0.25- case badRate > 0.01 && badCount >= 10000:- volumeScore = 0.75- case badRate > 0.01 && badCount >= 2000:- volumeScore = 0.50- case badRate > 0.01 && badCount >= 500:- volumeScore = 0.25- }-- return math.Max(apdexScore, math.Max(errorRateScore, math.Max(p99Score, math.Max(clientErrorScore, volumeScore))))-}-func sortEndpointStats(stats []models.EndpointStats, orderBy string, sortDirection string) {desc := sortDirection != "asc"@@ -948,7 +870,7 @@ func sortEndpointStats(stats []models.EndpointStats, orderBy string, sortDirecti}func getTopEndpointsByMetric(ctx context.Context, projectId uuid.UUID, from, to time.Time, metricType string) ([]string, error) {- params := lit.P{"project_id": projectId, "from": NewSQLiteTime(from), "to": NewSQLiteTime(to)}+ params := lit.P{"project_id": projectId, "from": sqlitetypes.NewSQLiteTime(from), "to": sqlitetypes.NewSQLiteTime(to)}if metricType == "total_time" {results, err := lit.SelectNamed[endpointMetricRow](db.TelemetryDB,@@ -993,7 +915,7 @@ func getTopEndpointsByMetric(ctx context.Context, projectId uuid.UUID, from, toif err != nil {return nil, err}- val := computePercentile(durations, percentile) / 1000000.0+ val := shared.ComputePercentile(durations, percentile) / 1000000.0metrics = append(metrics, epMetric{endpoint: ep.Endpoint, value: val})}@@ -1028,10 +950,10 @@ func (e *endpointRepository) FindByDistributedTraceId(ctx context.Context, distrquery := `SELECT id, project_id, endpoint, duration, recorded_at, status_code, body_size, client_ip, attributes, app_version, server_name, distributed_trace_idFROM endpoints WHERE distributed_trace_id = :trace_id AND project_id IN (` + strings.Join(placeholders, ",") + `)`if recordedAt != nil {- from, to := distributedTraceWindowBounds(*recordedAt)+ from, to := shared.DistributedTraceWindowBounds(*recordedAt)query += ` AND recorded_at >= :from AND recorded_at <= :to`- params["from"] = NewSQLiteTime(from)- params["to"] = NewSQLiteTime(to)+ params["from"] = sqlitetypes.NewSQLiteTime(from)+ params["to"] = sqlitetypes.NewSQLiteTime(to)}query += ` ORDER BY recorded_at ASC`@@ -1058,4 +980,4 @@ func (e *endpointRepository) FindByDistributedTraceId(ctx context.Context, distrreturn endpoints, nil}-var EndpointRepository = endpointRepository{}+var EndpointRepository = &endpointRepository{}diff --git a/backend/app/repositories/exception_stack_trace.repository_sqlite.go b/backend/app/repositories/telemetry/sqlite/exception_stack_trace.repository.gosimilarity index 85%rename from backend/app/repositories/exception_stack_trace.repository_sqlite.gorename to backend/app/repositories/telemetry/sqlite/exception_stack_trace.repository.goindex 8eb169fd..ab58b51a 100644--- a/backend/app/repositories/exception_stack_trace.repository_sqlite.go+++ b/backend/app/repositories/telemetry/sqlite/exception_stack_trace.repository.go@@ -1,12 +1,12 @@-//go:build !pgch+//go:build !telemetry_ch && !telemetry_duckdb-package repositories+package sqliteimport ("context"- "database/sql"- "errors""fmt"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/shared"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/sqlitetypes""strings""time"@@ -17,19 +17,19 @@ import ()type exceptionRow struct {- Id uuid.UUID `lit:"id"`- ProjectId uuid.UUID `lit:"project_id"`- TraceId *uuid.UUID `lit:"trace_id"`- TraceType string `lit:"trace_type"`- ExceptionHash string `lit:"exception_hash"`- StackTrace string `lit:"stack_trace"`- RecordedAt SQLiteTime `lit:"recorded_at"`- Attributes SQLiteJSONMap `lit:"attributes"`- AppVersion string `lit:"app_version"`- ServerName string `lit:"server_name"`- IsMessage bool `lit:"is_message"`- DistributedTraceId *uuid.UUID `lit:"distributed_trace_id"`- SessionId *uuid.UUID `lit:"session_id"`+ Id uuid.UUID `lit:"id"`+ ProjectId uuid.UUID `lit:"project_id"`+ TraceId *uuid.UUID `lit:"trace_id"`+ TraceType string `lit:"trace_type"`+ ExceptionHash string `lit:"exception_hash"`+ StackTrace string `lit:"stack_trace"`+ RecordedAt sqlitetypes.SQLiteTime `lit:"recorded_at"`+ Attributes sqlitetypes.SQLiteJSONMap `lit:"attributes"`+ AppVersion string `lit:"app_version"`+ ServerName string `lit:"server_name"`+ IsMessage bool `lit:"is_message"`+ DistributedTraceId *uuid.UUID `lit:"distributed_trace_id"`+ SessionId *uuid.UUID `lit:"session_id"`}type exceptionRowNaming struct{ lit.DefaultDbNamingStrategy }@@ -39,18 +39,18 @@ func (exceptionRowNaming) GetTableNameFromStructName(string) string {}type exceptionGroupRow struct {- ExceptionHash string `lit:"exception_hash"`- StackTrace string `lit:"stack_trace"`- LastSeen string `lit:"last_seen"`- FirstSeen string `lit:"first_seen"`- Count uint64 `lit:"count"`+ ExceptionHash string `lit:"exception_hash"`+ StackTrace string `lit:"stack_trace"`+ LastSeen string `lit:"last_seen"`+ FirstSeen string `lit:"first_seen"`+ Count uint64 `lit:"count"`MaxArchivedAt *string `lit:"max_archived_at"`}type exceptionTrendRow struct {- Hash string `lit:"exception_hash"`- Hour string `lit:"hour"`- Count uint64 `lit:"count"`+ Hash string `lit:"exception_hash"`+ Hour string `lit:"hour"`+ Count uint64 `lit:"count"`}func init() {@@ -73,8 +73,8 @@ func exceptionToRow(est models.ExceptionStackTrace) exceptionRow {TraceType: traceType,ExceptionHash: est.ExceptionHash,StackTrace: est.StackTrace,- RecordedAt: NewSQLiteTime(est.RecordedAt),- Attributes: NewSQLiteJSONMap(est.Attributes),+ RecordedAt: sqlitetypes.NewSQLiteTime(est.RecordedAt),+ Attributes: sqlitetypes.NewSQLiteJSONMap(est.Attributes),AppVersion: est.AppVersion,ServerName: est.ServerName,IsMessage: est.IsMessage,@@ -130,7 +130,7 @@ func (e *exceptionStackTraceRepository) InsertAsync(ctx context.Context, lines [func (e *exceptionStackTraceRepository) CountBetween(ctx context.Context, projectId uuid.UUID, start, end time.Time) (int64, error) {result, err := lit.SelectSingleNamed[models.CountResult](db.TelemetryDB,"SELECT COUNT(*) AS count FROM exception_stack_traces WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to",- lit.P{"project_id": projectId, "from": NewSQLiteTime(start), "to": NewSQLiteTime(end)})+ lit.P{"project_id": projectId, "from": sqlitetypes.NewSQLiteTime(start), "to": sqlitetypes.NewSQLiteTime(end)})if err != nil {return 0, err}@@ -154,7 +154,7 @@ func (e *exceptionStackTraceRepository) FindGrouped(ctx context.Context, projectorderBy = "count"}- params := lit.P{"project_id": projectId, "from": NewSQLiteTime(fromDate), "to": NewSQLiteTime(toDate)}+ params := lit.P{"project_id": projectId, "from": sqlitetypes.NewSQLiteTime(fromDate), "to": sqlitetypes.NewSQLiteTime(toDate)}whereClause := "e.project_id = :project_id AND e.recorded_at >= :from AND e.recorded_at <= :to"if search != "" {@@ -233,9 +233,6 @@ func (e *exceptionStackTraceRepository) FindByHash(ctx context.Context, projectIGROUP BY exception_hash`,params)if err != nil {- if errors.Is(err, sql.ErrNoRows) {- return nil, nil, 0, nil- }return nil, nil, 0, err}if groupRow == nil {@@ -270,28 +267,28 @@ func (e *exceptionStackTraceRepository) FindByHash(ctx context.Context, projectI}func (e *exceptionStackTraceRepository) CountByHour(ctx context.Context, projectId uuid.UUID, start, end time.Time) ([]models.TimeSeriesPoint, error) {- results, err := lit.SelectNamed[timeSeriesResult](db.TelemetryDB,+ results, err := lit.SelectNamed[sqlitetypes.TimeSeriesResult](db.TelemetryDB,`SELECT strftime('%Y-%m-%d %H:00:00', recorded_at) as bucket, CAST(COUNT(*) AS REAL) as agg_valueFROM exception_stack_traces WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :toGROUP BY bucket ORDER BY bucket ASC`,- lit.P{"project_id": projectId, "from": NewSQLiteTime(start), "to": NewSQLiteTime(end)})+ lit.P{"project_id": projectId, "from": sqlitetypes.NewSQLiteTime(start), "to": sqlitetypes.NewSQLiteTime(end)})if err != nil {return nil, err}- return timeSeriesResultsToPoints(results), nil+ return sqlitetypes.TimeSeriesResultsToPoints(results), nil}func (e *exceptionStackTraceRepository) CountByInterval(ctx context.Context, projectId uuid.UUID, start, end time.Time, intervalMinutes int) ([]models.TimeSeriesPoint, error) {intervalSeconds := intervalMinutes * 60- results, err := lit.SelectNamed[timeSeriesResult](db.TelemetryDB,+ results, err := lit.SelectNamed[sqlitetypes.TimeSeriesResult](db.TelemetryDB,fmt.Sprintf(`SELECT datetime((strftime('%%s', recorded_at) / %d) * %d, 'unixepoch') as bucket, CAST(COUNT(*) AS REAL) as agg_valueFROM exception_stack_traces WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :toGROUP BY bucket ORDER BY bucket ASC`, intervalSeconds, intervalSeconds),- lit.P{"project_id": projectId, "from": NewSQLiteTime(start), "to": NewSQLiteTime(end)})+ lit.P{"project_id": projectId, "from": sqlitetypes.NewSQLiteTime(start), "to": sqlitetypes.NewSQLiteTime(end)})if err != nil {return nil, err}- return timeSeriesResultsToPoints(results), nil+ return sqlitetypes.TimeSeriesResultsToPoints(results), nil}func (e *exceptionStackTraceRepository) GetHourlyTrendForHashes(ctx context.Context, projectId uuid.UUID, hashes []string, start, end time.Time) (map[string][]models.ExceptionTrendPoint, error) {@@ -299,7 +296,7 @@ func (e *exceptionStackTraceRepository) GetHourlyTrendForHashes(ctx context.Contreturn make(map[string][]models.ExceptionTrendPoint), nil}- params := lit.P{"project_id": projectId, "from": NewSQLiteTime(start), "to": NewSQLiteTime(end)}+ params := lit.P{"project_id": projectId, "from": sqlitetypes.NewSQLiteTime(start), "to": sqlitetypes.NewSQLiteTime(end)}placeholders := make([]string, len(hashes))for i, h := range hashes {key := fmt.Sprintf("hash_%d", i)@@ -335,7 +332,7 @@ func (e *exceptionStackTraceRepository) ArchiveByHashes(ctx context.Context, proreturn nil}- now := NewSQLiteTime(time.Now().UTC())+ now := sqlitetypes.NewSQLiteTime(time.Now().UTC())for _, hash := range hashes {query, args, err := lit.ParseNamedQuery(db.Driver,"INSERT OR REPLACE INTO archived_exceptions (project_id, exception_hash, archived_at) VALUES (:project_id, :exception_hash, :archived_at)",@@ -407,10 +404,10 @@ func (e *exceptionStackTraceRepository) FindAllByTraceId(ctx context.Context, prFROM exception_stack_traces WHERE project_id = :project_id AND trace_id = :trace_id`params := lit.P{"project_id": projectId, "trace_id": traceId}if recordedAt != nil {- from, to := traceWindowBounds(*recordedAt)+ from, to := shared.TraceWindowBounds(*recordedAt)query += ` AND recorded_at >= :from AND recorded_at <= :to`- params["from"] = NewSQLiteTime(from)- params["to"] = NewSQLiteTime(to)+ params["from"] = sqlitetypes.NewSQLiteTime(from)+ params["to"] = sqlitetypes.NewSQLiteTime(to)}query += ` ORDER BY recorded_at ASC`@@ -431,10 +428,10 @@ func (e *exceptionStackTraceRepository) FindById(ctx context.Context, projectIdFROM exception_stack_traces WHERE project_id = :project_id AND id = :id`params := lit.P{"project_id": projectId, "id": id}if recordedAt != nil {- from, to := traceWindowBounds(*recordedAt)+ from, to := shared.TraceWindowBounds(*recordedAt)query += ` AND recorded_at >= :from AND recorded_at <= :to`- params["from"] = NewSQLiteTime(from)- params["to"] = NewSQLiteTime(to)+ params["from"] = sqlitetypes.NewSQLiteTime(from)+ params["to"] = sqlitetypes.NewSQLiteTime(to)}query += ` LIMIT 1`@@ -464,10 +461,10 @@ func (e *exceptionStackTraceRepository) FindByDistributedTraceId(ctx context.Conquery := `SELECT id, project_id, trace_id, trace_type, exception_hash, stack_trace, recorded_at, attributes, app_version, server_name, is_message, distributed_trace_id, session_idFROM exception_stack_traces WHERE distributed_trace_id = :trace_id AND project_id IN (` + strings.Join(placeholders, ",") + `) AND is_message = 0`if recordedAt != nil {- from, to := distributedTraceWindowBounds(*recordedAt)+ from, to := shared.DistributedTraceWindowBounds(*recordedAt)query += ` AND recorded_at >= :from AND recorded_at <= :to`- params["from"] = NewSQLiteTime(from)- params["to"] = NewSQLiteTime(to)+ params["from"] = sqlitetypes.NewSQLiteTime(from)+ params["to"] = sqlitetypes.NewSQLiteTime(to)}query += ` ORDER BY recorded_at ASC`@@ -525,4 +522,4 @@ func (e *exceptionStackTraceRepository) GetSessionIdForException(ctx context.Conreturn row.SessionId, nil}-var ExceptionStackTraceRepository = exceptionStackTraceRepository{}+var ExceptionStackTraceRepository = &exceptionStackTraceRepository{}diff --git a/backend/app/repositories/fired_notification.repository_sqlite.go b/backend/app/repositories/telemetry/sqlite/fired_notification.repository.gosimilarity index 78%rename from backend/app/repositories/fired_notification.repository_sqlite.gorename to backend/app/repositories/telemetry/sqlite/fired_notification.repository.goindex fa2bb85f..ca97b8c7 100644--- a/backend/app/repositories/fired_notification.repository_sqlite.go+++ b/backend/app/repositories/telemetry/sqlite/fired_notification.repository.go@@ -1,9 +1,11 @@-//go:build !pgch+//go:build !telemetry_ch && !telemetry_duckdb-package repositories+package sqliteimport ("context"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/shared"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/sqlitetypes""strings""time"@@ -13,38 +15,21 @@ import ("github.com/tracewayapp/traceway/backend/app/models")-type FiredNotification struct {- ProjectId uuid.UUID- RuleId int- RuleType string- RuleName string- ChannelType string- ChannelName string- Severity string- Subject string- Body string- Status string- ErrorMsg string- Endpoint string- URL string- FiredAt time.Time-}-type firedNotificationRow struct {- ProjectId uuid.UUID `lit:"project_id"`- RuleId int `lit:"rule_id"`- RuleType string `lit:"rule_type"`- RuleName string `lit:"rule_name"`- ChannelType string `lit:"channel_type"`- ChannelName string `lit:"channel_name"`- Severity string `lit:"severity"`- Subject string `lit:"subject"`- Body string `lit:"body"`- Status string `lit:"status"`- ErrorMsg string `lit:"error_message"`- Endpoint string `lit:"endpoint"`- URL string `lit:"url"`- FiredAt SQLiteTime `lit:"fired_at"`+ ProjectId uuid.UUID `lit:"project_id"`+ RuleId int `lit:"rule_id"`+ RuleType string `lit:"rule_type"`+ RuleName string `lit:"rule_name"`+ ChannelType string `lit:"channel_type"`+ ChannelName string `lit:"channel_name"`+ Severity string `lit:"severity"`+ Subject string `lit:"subject"`+ Body string `lit:"body"`+ Status string `lit:"status"`+ ErrorMsg string `lit:"error_message"`+ Endpoint string `lit:"endpoint"`+ URL string `lit:"url"`+ FiredAt sqlitetypes.SQLiteTime `lit:"fired_at"`}func init() {@@ -55,7 +40,7 @@ func init() {type firedNotificationRepository struct{}-func (r *firedNotificationRepository) Insert(ctx context.Context, n FiredNotification) error {+func (r *firedNotificationRepository) Insert(ctx context.Context, n shared.FiredNotification) error {row := firedNotificationRow{ProjectId: n.ProjectId,RuleId: n.RuleId,@@ -70,7 +55,7 @@ func (r *firedNotificationRepository) Insert(ctx context.Context, n FiredNotificErrorMsg: n.ErrorMsg,Endpoint: n.Endpoint,URL: n.URL,- FiredAt: NewSQLiteTime(n.FiredAt),+ FiredAt: sqlitetypes.NewSQLiteTime(n.FiredAt),}query, args, err := lit.ParseNamedQuery(db.Driver,@@ -135,7 +120,7 @@ func (r *firedNotificationRepository) FindByProject(ctx context.Context, projectvar items []*models.NotificationHistoryEntryfor rows.Next() {entry := &models.NotificationHistoryEntry{}- var firedAt SQLiteTime+ var firedAt sqlitetypes.SQLiteTimeif err := rows.Scan(&entry.RuleId, &entry.RuleType, &entry.RuleName, &entry.ChannelType, &entry.ChannelName,&entry.Severity, &entry.Subject, &entry.Body, &entry.Status, &entry.ErrorMessage,@@ -163,7 +148,7 @@ func (r *firedNotificationRepository) FindLastFiredPerRule(ctx context.Context)result := make(map[int]time.Time)for rows.Next() {var ruleId int- var firedAt SQLiteTime+ var firedAt sqlitetypes.SQLiteTimeif err := rows.Scan(&ruleId, &firedAt); err != nil {return nil, err}@@ -176,4 +161,4 @@ func (r *firedNotificationRepository) FindLastFiredPerRule(ctx context.Context)return result, nil}-var FiredNotificationRepository = firedNotificationRepository{}+var FiredNotificationRepository = &firedNotificationRepository{}diff --git a/backend/app/repositories/log_record.repository_sqlite.go b/backend/app/repositories/telemetry/sqlite/log_record.repository.gosimilarity index 76%rename from backend/app/repositories/log_record.repository_sqlite.gorename to backend/app/repositories/telemetry/sqlite/log_record.repository.goindex 63d4feec..758c1db2 100644--- a/backend/app/repositories/log_record.repository_sqlite.go+++ b/backend/app/repositories/telemetry/sqlite/log_record.repository.go@@ -1,12 +1,13 @@-//go:build !pgch+//go:build !telemetry_ch && !telemetry_duckdb-package repositories+package sqliteimport ("context""fmt"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/shared"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/sqlitetypes""strings"- "time""github.com/google/uuid""github.com/tracewayapp/lit/v2"@@ -15,49 +16,24 @@ import ("github.com/tracewayapp/traceway/backend/app/models")-// LogAttributeFilter — see the ClickHouse-side definition. Kept identical here-// so callers don't need a build-tag guard.-type LogAttributeFilter struct {- Scope string- Key string- Value string-}--type LogSearchParams struct {- ProjectId uuid.UUID- FromDate time.Time- ToDate time.Time- Search string- SearchType string- MinSeverity uint8- ServiceName string- TraceId string- TraceIds []string- AttributeFilters []LogAttributeFilter- OrderBy string- SortDirection string- Page int- PageSize int-}-type logRecord struct {- Id uuid.UUID `lit:"id"`- ProjectId uuid.UUID `lit:"project_id"`- Timestamp SQLiteTime `lit:"timestamp"`- TraceId string `lit:"trace_id"`- SpanId string `lit:"span_id"`- TraceFlags uint8 `lit:"trace_flags"`- SeverityText string `lit:"severity_text"`- SeverityNumber uint8 `lit:"severity_number"`- ServiceName string `lit:"service_name"`- Body string `lit:"body"`- ResourceSchemaUrl string `lit:"resource_schema_url"`- ResourceAttributes SQLiteJSONMap `lit:"resource_attributes"`- ScopeSchemaUrl string `lit:"scope_schema_url"`- ScopeName string `lit:"scope_name"`- ScopeVersion string `lit:"scope_version"`- ScopeAttributes SQLiteJSONMap `lit:"scope_attributes"`- LogAttributes SQLiteJSONMap `lit:"log_attributes"`+ Id uuid.UUID `lit:"id"`+ ProjectId uuid.UUID `lit:"project_id"`+ Timestamp sqlitetypes.SQLiteTime `lit:"timestamp"`+ TraceId string `lit:"trace_id"`+ SpanId string `lit:"span_id"`+ TraceFlags uint8 `lit:"trace_flags"`+ SeverityText string `lit:"severity_text"`+ SeverityNumber uint8 `lit:"severity_number"`+ ServiceName string `lit:"service_name"`+ Body string `lit:"body"`+ ResourceSchemaUrl string `lit:"resource_schema_url"`+ ResourceAttributes sqlitetypes.SQLiteJSONMap `lit:"resource_attributes"`+ ScopeSchemaUrl string `lit:"scope_schema_url"`+ ScopeName string `lit:"scope_name"`+ ScopeVersion string `lit:"scope_version"`+ ScopeAttributes sqlitetypes.SQLiteJSONMap `lit:"scope_attributes"`+ LogAttributes sqlitetypes.SQLiteJSONMap `lit:"log_attributes"`}func init() {@@ -70,7 +46,7 @@ func logRecordToRow(lr models.LogRecord) logRecord {return logRecord{Id: lr.Id,ProjectId: lr.ProjectId,- Timestamp: NewSQLiteTime(lr.Timestamp),+ Timestamp: sqlitetypes.NewSQLiteTime(lr.Timestamp),TraceId: lr.TraceId,SpanId: lr.SpanId,TraceFlags: lr.TraceFlags,@@ -79,12 +55,12 @@ func logRecordToRow(lr models.LogRecord) logRecord {ServiceName: lr.ServiceName,Body: lr.Body,ResourceSchemaUrl: lr.ResourceSchemaUrl,- ResourceAttributes: NewSQLiteJSONMap(lr.ResourceAttributes),+ ResourceAttributes: sqlitetypes.NewSQLiteJSONMap(lr.ResourceAttributes),ScopeSchemaUrl: lr.ScopeSchemaUrl,ScopeName: lr.ScopeName,ScopeVersion: lr.ScopeVersion,- ScopeAttributes: NewSQLiteJSONMap(lr.ScopeAttributes),- LogAttributes: NewSQLiteJSONMap(lr.LogAttributes),+ ScopeAttributes: sqlitetypes.NewSQLiteJSONMap(lr.ScopeAttributes),+ LogAttributes: sqlitetypes.NewSQLiteJSONMap(lr.LogAttributes),}}@@ -139,7 +115,7 @@ func (r *logRecordRepository) InsertAsync(ctx context.Context, records []models.return tx.Commit()}-func (r *logRecordRepository) Search(ctx context.Context, params LogSearchParams) ([]models.LogRecord, int64, error) {+func (r *logRecordRepository) Search(ctx context.Context, params shared.LogSearchParams) ([]models.LogRecord, int64, error) {where, args := r.buildWhere(params)countResult, err := lit.SelectSingleNamed[models.CountResult](db.TelemetryDB,@@ -216,12 +192,12 @@ func (r *logRecordRepository) FindByTraceId(ctx context.Context, projectId uuid.return records, nil}-func (r *logRecordRepository) buildWhere(params LogSearchParams) (string, lit.P) {+func (r *logRecordRepository) buildWhere(params shared.LogSearchParams) (string, lit.P) {clauses := []string{"project_id = :project_id", "timestamp >= :from", "timestamp <= :to"}args := lit.P{"project_id": params.ProjectId,- "from": NewSQLiteTime(params.FromDate),- "to": NewSQLiteTime(params.ToDate),+ "from": sqlitetypes.NewSQLiteTime(params.FromDate),+ "to": sqlitetypes.NewSQLiteTime(params.ToDate),}if params.MinSeverity > 0 {@@ -302,4 +278,4 @@ func (r *logRecordRepository) resolveOrderBy(orderBy string) string {return "timestamp"}-var LogRecordRepository = logRecordRepository{}+var LogRecordRepository = &logRecordRepository{}diff --git a/backend/app/repositories/metric_point.repository_sqlite.go b/backend/app/repositories/telemetry/sqlite/metric_point.repository.gosimilarity index 89%rename from backend/app/repositories/metric_point.repository_sqlite.gorename to backend/app/repositories/telemetry/sqlite/metric_point.repository.goindex 92b5ab6f..acae1f93 100644--- a/backend/app/repositories/metric_point.repository_sqlite.go+++ b/backend/app/repositories/telemetry/sqlite/metric_point.repository.go@@ -1,11 +1,12 @@-//go:build !pgch+//go:build !telemetry_ch && !telemetry_duckdb-package repositories+package sqliteimport ("context""database/sql""fmt"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/sqlitetypes""strings""time"@@ -13,6 +14,7 @@ import ("github.com/tracewayapp/lit/v2""github.com/tracewayapp/traceway/backend/app/db""github.com/tracewayapp/traceway/backend/app/models"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/shared")type metricPointRepository struct{}@@ -44,7 +46,7 @@ func (r *metricPointRepository) InsertAsync(ctx context.Context, points []modelsdefer tx.Rollback()for _, p := range points {- tags := NewSQLiteJSONMap(p.Tags)+ tags := sqlitetypes.NewSQLiteJSONMap(p.Tags)tagsVal, _ := tags.Value()query, args, err := lit.ParseNamedQuery(db.Driver,"INSERT INTO metric_points (project_id, name, value, tags, recorded_at) VALUES (:project_id, :name, :value, :tags, :recorded_at)",@@ -53,7 +55,7 @@ func (r *metricPointRepository) InsertAsync(ctx context.Context, points []models"name": p.Name,"value": p.Value,"tags": tagsVal,- "recorded_at": NewSQLiteTime(p.RecordedAt),+ "recorded_at": sqlitetypes.NewSQLiteTime(p.RecordedAt),})if err != nil {return err@@ -80,15 +82,15 @@ func (r *metricPointRepository) QueryTimeSeries(ctx context.Context, projectId uparams := lit.P{"project_id": projectId,"name": name,- "from": NewSQLiteTime(from),- "to": NewSQLiteTime(to),+ "from": sqlitetypes.NewSQLiteTime(from),+ "to": sqlitetypes.NewSQLiteTime(to),}if hasGroupBy {params["group_by"] = groupBy}filterClauses := ""- for i, k := range sortedKeys(tagFilters) {+ for i, k := range shared.SortedKeys(tagFilters) {fk := fmt.Sprintf("fk_%d", i)fv := fmt.Sprintf("fv_%d", i)filterClauses += fmt.Sprintf(" AND json_extract(tags, '$.\"' || :%s || '\"') = :%s", fk, fv)@@ -157,7 +159,7 @@ func (r *metricPointRepository) DiscoverMetrics(ctx context.Context, projectId uWHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :toGROUP BY name, j.keyORDER BY name ASC, j.key ASC`,- lit.P{"project_id": projectId, "from": NewSQLiteTime(from), "to": NewSQLiteTime(to)})+ lit.P{"project_id": projectId, "from": sqlitetypes.NewSQLiteTime(from), "to": sqlitetypes.NewSQLiteTime(to)})if err != nil {return nil, err}@@ -207,7 +209,7 @@ func (r *metricPointRepository) DiscoverTagValues(ctx context.Context, projectIdAND json_extract(tags, '$."' || :tag_key || '"') IS NOT NULLAND json_extract(tags, '$."' || :tag_key || '"') != ''ORDER BY tag_value ASC`,- lit.P{"project_id": projectId, "name": metricName, "tag_key": tagKey, "from": NewSQLiteTime(from), "to": NewSQLiteTime(to)})+ lit.P{"project_id": projectId, "name": metricName, "tag_key": tagKey, "from": sqlitetypes.NewSQLiteTime(from), "to": sqlitetypes.NewSQLiteTime(to)})if err != nil {return nil, err}@@ -222,7 +224,7 @@ func (r *metricPointRepository) DiscoverTagValues(ctx context.Context, projectIdfunc (r *metricPointRepository) GetAverageBetween(ctx context.Context, projectId uuid.UUID, name string, start, end time.Time) (float64, error) {result, err := lit.SelectSingleNamed[avgResult](db.TelemetryDB,"SELECT COALESCE(avg(value), 0) AS agg_value FROM metric_points WHERE project_id = :project_id AND name = :name AND recorded_at >= :from AND recorded_at <= :to",- lit.P{"project_id": projectId, "name": name, "from": NewSQLiteTime(start), "to": NewSQLiteTime(end)})+ lit.P{"project_id": projectId, "name": name, "from": sqlitetypes.NewSQLiteTime(start), "to": sqlitetypes.NewSQLiteTime(end)})if err != nil {return 0, err}@@ -240,7 +242,7 @@ func (r *metricPointRepository) GetDistinctServers(ctx context.Context, projectIAND json_extract(tags, '$.server_name') IS NOT NULLAND json_extract(tags, '$.server_name') != ''ORDER BY sn ASC`,- lit.P{"project_id": projectId, "from": NewSQLiteTime(start), "to": NewSQLiteTime(end)})+ lit.P{"project_id": projectId, "from": sqlitetypes.NewSQLiteTime(start), "to": sqlitetypes.NewSQLiteTime(end)})if err != nil {return nil, err}@@ -258,8 +260,8 @@ func (r *metricPointRepository) GetAverageByIntervalPerServer(ctx context.Contexparams := lit.P{"project_id": projectId,"name": name,- "from": NewSQLiteTime(start),- "to": NewSQLiteTime(end),+ "from": sqlitetypes.NewSQLiteTime(start),+ "to": sqlitetypes.NewSQLiteTime(end),}query := fmt.Sprintf(`SELECT@@ -331,12 +333,4 @@ func sqliteAggregationFunc(agg string) string {}}-func sortedKeys(m map[string]string) []string {- keys := make([]string, 0, len(m))- for k := range m {- keys = append(keys, k)- }- return keys-}--var MetricPointRepository = metricPointRepository{}+var MetricPointRepository = &metricPointRepository{}diff --git a/backend/app/repositories/profile.repository_sqlite.go b/backend/app/repositories/telemetry/sqlite/profile.repository.gosimilarity index 85%rename from backend/app/repositories/profile.repository_sqlite.gorename to backend/app/repositories/telemetry/sqlite/profile.repository.goindex 439d6e03..d72d3142 100644--- a/backend/app/repositories/profile.repository_sqlite.go+++ b/backend/app/repositories/telemetry/sqlite/profile.repository.go@@ -1,11 +1,13 @@-//go:build !pgch+//go:build !telemetry_ch && !telemetry_duckdb-package repositories+package sqliteimport ("context""encoding/json""fmt"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/shared"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/sqlitetypes""sort""time"@@ -17,14 +19,14 @@ import ()type profileGroupRow struct {- ServiceName string `lit:"service_name"`- ProfileType string `lit:"profile_type"`- Unit string `lit:"unit"`- IsGauge int64 `lit:"is_gauge"`- ProfileCount int64 `lit:"profile_count"`- SampleCount int64 `lit:"sample_count"`- TotalValue int64 `lit:"total_value"`- LastSeen SQLiteTime `lit:"last_seen"`+ ServiceName string `lit:"service_name"`+ ProfileType string `lit:"profile_type"`+ Unit string `lit:"unit"`+ IsGauge int64 `lit:"is_gauge"`+ ProfileCount int64 `lit:"profile_count"`+ SampleCount int64 `lit:"sample_count"`+ TotalValue int64 `lit:"total_value"`+ LastSeen sqlitetypes.SQLiteTime `lit:"last_seen"`}type labelValueRow struct {@@ -82,7 +84,7 @@ func (r *profileRepository) InsertStacksAsync(ctx context.Context, stacks []mode"service_name": s.ServiceName,"stack_hash": int64(s.StackHash),"stack": string(stackJSON),- "last_seen": NewSQLiteTime(s.LastSeen),+ "last_seen": sqlitetypes.NewSQLiteTime(s.LastSeen),})if err != nil {return err@@ -105,7 +107,7 @@ func (r *profileRepository) InsertSamplesAsync(ctx context.Context, samples []modefer tx.Rollback()for _, s := range samples {- labelsVal, _ := NewSQLiteJSONMap(s.Labels).Value()+ labelsVal, _ := sqlitetypes.NewSQLiteJSONMap(s.Labels).Value()query, args, err := lit.ParseNamedQuery(db.Driver,"INSERT INTO profiling_samples (project_id, profile_id, service_name, type, unit, is_gauge, start_time, end_time, stack_hash, value, labels, server_name, app_version, trace_id, span_id) VALUES (:project_id, :profile_id, :service_name, :type, :unit, :is_gauge, :start_time, :end_time, :stack_hash, :value, :labels, :server_name, :app_version, :trace_id, :span_id)",lit.P{@@ -115,8 +117,8 @@ func (r *profileRepository) InsertSamplesAsync(ctx context.Context, samples []mo"type": s.Type,"unit": s.Unit,"is_gauge": boolToInt(s.IsGauge),- "start_time": NewSQLiteTime(s.Start),- "end_time": NewSQLiteTime(s.End),+ "start_time": sqlitetypes.NewSQLiteTime(s.Start),+ "end_time": sqlitetypes.NewSQLiteTime(s.End),"stack_hash": int64(s.StackHash),"value": s.Value,"labels": labelsVal,@@ -146,13 +148,13 @@ func (r *profileRepository) InsertProfilesAsync(ctx context.Context, profiles []defer tx.Rollback()for _, p := range profiles {- attributesVal, _ := NewSQLiteJSONMap(p.Attributes).Value()+ attributesVal, _ := sqlitetypes.NewSQLiteJSONMap(p.Attributes).Value()query, args, err := lit.ParseNamedQuery(db.Driver,"INSERT INTO profiles (id, project_id, recorded_at, duration, service_name, profile_type, unit, is_gauge, sample_count, total_value, server_name, app_version, attributes, storage_key, trace_id, span_id, distributed_trace_id) VALUES (:id, :project_id, :recorded_at, :duration, :service_name, :profile_type, :unit, :is_gauge, :sample_count, :total_value, :server_name, :app_version, :attributes, :storage_key, :trace_id, :span_id, :distributed_trace_id)",lit.P{"id": p.Id,"project_id": p.ProjectId,- "recorded_at": NewSQLiteTime(p.RecordedAt),+ "recorded_at": sqlitetypes.NewSQLiteTime(p.RecordedAt),"duration": int64(p.Duration),"service_name": p.ServiceName,"profile_type": p.ProfileType,@@ -180,7 +182,7 @@ func (r *profileRepository) InsertProfilesAsync(ctx context.Context, profiles []func (r *profileRepository) FindGroupedByService(ctx context.Context, projectId uuid.UUID, from, to time.Time, page, pageSize int, orderBy, sortDirection, search string) ([]models.ProfileGroup, int64, error) {searchClause := ""- countParams := lit.P{"project_id": projectId, "from": NewSQLiteTime(from), "to": NewSQLiteTime(to)}+ countParams := lit.P{"project_id": projectId, "from": sqlitetypes.NewSQLiteTime(from), "to": sqlitetypes.NewSQLiteTime(to)}if search != "" {searchClause = " AND instr(lower(service_name), lower(:search)) > 0"countParams["search"] = search@@ -215,7 +217,7 @@ func (r *profileRepository) FindGroupedByService(ctx context.Context, projectId}offset := (page - 1) * pageSize- pageParams := lit.P{"project_id": projectId, "from": NewSQLiteTime(from), "to": NewSQLiteTime(to), "limit": pageSize, "offset": offset}+ pageParams := lit.P{"project_id": projectId, "from": sqlitetypes.NewSQLiteTime(from), "to": sqlitetypes.NewSQLiteTime(to), "limit": pageSize, "offset": offset}if search != "" {pageParams["search"] = search}@@ -275,7 +277,7 @@ func (r *profileRepository) fillSparklines(ctx context.Context, projectId uuid.UFROM profilesWHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :toGROUP BY service_name, profile_type, bucket`, bucketSecs, bucketSecs),- lit.P{"project_id": projectId, "from": NewSQLiteTime(from), "to": NewSQLiteTime(to)})+ lit.P{"project_id": projectId, "from": sqlitetypes.NewSQLiteTime(from), "to": sqlitetypes.NewSQLiteTime(to)})if err != nil {return err}@@ -330,7 +332,7 @@ func (r *profileRepository) DiscoverTypes(ctx context.Context, projectId uuid.UUAND start_time >= :from AND start_time <= :toGROUP BY typeORDER BY type ASC`,- lit.P{"project_id": projectId, "service": service, "from": NewSQLiteTime(from), "to": NewSQLiteTime(to)})+ lit.P{"project_id": projectId, "service": service, "from": sqlitetypes.NewSQLiteTime(from), "to": sqlitetypes.NewSQLiteTime(to)})if err != nil {return nil, err}@@ -352,11 +354,11 @@ func (r *profileRepository) GetSeries(ctx context.Context, projectId uuid.UUID,agg = "AVG"}- params := lit.P{"project_id": projectId, "type": profileType, "service": service, "from": NewSQLiteTime(from), "to": NewSQLiteTime(to)}+ params := lit.P{"project_id": projectId, "type": profileType, "service": service, "from": sqlitetypes.NewSQLiteTime(from), "to": sqlitetypes.NewSQLiteTime(to)}filter := sqliteLabelFilter("", labelFilters, params)cohort := sqliteCohortFilter("", appVersion, serverName, params)- results, err := lit.SelectNamed[timeSeriesResult](db.TelemetryDB,+ results, err := lit.SelectNamed[sqlitetypes.TimeSeriesResult](db.TelemetryDB,fmt.Sprintf(`SELECT datetime((strftime('%%s', start_time) / %d) * %d, 'unixepoch') AS bucket,CAST(%s(value) AS REAL) AS agg_valueFROM profiling_samples@@ -367,13 +369,13 @@ func (r *profileRepository) GetSeries(ctx context.Context, projectId uuid.UUID,if err != nil {return nil, err}- points := timeSeriesResultsToPoints(results)- normalizeSeriesPoints(points, normalize, isGauge, intervalMinutes)+ points := sqlitetypes.TimeSeriesResultsToPoints(results)+ shared.NormalizeSeriesPoints(points, normalize, isGauge, intervalMinutes)return points, nil}func (r *profileRepository) GetFlameGraph(ctx context.Context, projectId uuid.UUID, service, profileType string, from, to time.Time, labelFilters map[string]string, isGauge bool, appVersion, serverName string) ([]models.ProfileStackValue, error) {- params := lit.P{"project_id": projectId, "type": profileType, "service": service, "from": NewSQLiteTime(from), "to": NewSQLiteTime(to)}+ params := lit.P{"project_id": projectId, "type": profileType, "service": service, "from": sqlitetypes.NewSQLiteTime(from), "to": sqlitetypes.NewSQLiteTime(to)}bareFilter := sqliteLabelFilter("", labelFilters, params)aliasFilter := sqliteLabelFilter("s.", labelFilters, params)bareCohort := sqliteCohortFilter("", appVersion, serverName, params)@@ -441,7 +443,7 @@ func (r *profileRepository) distinctLabelValues(ctx context.Context, projectId uAND json_extract(labels, '$."' || :key || '"') != ''ORDER BY v ASCLIMIT %d`, profiling.MaxLabelValuesPerKey),- lit.P{"project_id": projectId, "type": profileType, "service": service, "key": key, "from": NewSQLiteTime(from), "to": NewSQLiteTime(to)})+ lit.P{"project_id": projectId, "type": profileType, "service": service, "key": key, "from": sqlitetypes.NewSQLiteTime(from), "to": sqlitetypes.NewSQLiteTime(to)})if err != nil {return nil, err}@@ -458,13 +460,13 @@ func (r *profileRepository) GetSeriesBreakdown(ctx context.Context, projectId uuintervalMinutes = 1}secs := intervalMinutes * 60- limit = clampBreakdownLimit(limit)+ limit = shared.ClampBreakdownLimit(limit)agg := "SUM"if isGauge {agg = "AVG"}- params := lit.P{"project_id": projectId, "type": profileType, "service": service, "from": NewSQLiteTime(from), "to": NewSQLiteTime(to), "limit": limit}+ params := lit.P{"project_id": projectId, "type": profileType, "service": service, "from": sqlitetypes.NewSQLiteTime(from), "to": sqlitetypes.NewSQLiteTime(to), "limit": limit}filter := sqliteLabelFilter("", labelFilters, params)cohort := sqliteCohortFilter("", appVersion, serverName, params)dimExpr, ok := sqliteDimExpr(dimension, params)@@ -499,12 +501,12 @@ func (r *profileRepository) GetSeriesBreakdown(ctx context.Context, projectId uu}key := *row.Keyparams["dimval"] = key- results, err := lit.SelectNamed[timeSeriesResult](db.TelemetryDB, seriesQuery, params)+ results, err := lit.SelectNamed[sqlitetypes.TimeSeriesResult](db.TelemetryDB, seriesQuery, params)if err != nil {return nil, err}- points := timeSeriesResultsToPoints(results)- normalizeSeriesPoints(points, normalize, isGauge, intervalMinutes)+ points := sqlitetypes.TimeSeriesResultsToPoints(results)+ shared.NormalizeSeriesPoints(points, normalize, isGauge, intervalMinutes)groups = append(groups, models.ProfileSeriesGroup{Key: key, Points: points})}return groups, nil@@ -529,7 +531,7 @@ func (r *profileRepository) distinctDimensionValues(ctx context.Context, projectWHERE project_id = :project_id AND service_name = :service AND type = :typeAND start_time >= :from AND start_time <= :to AND %s != ''ORDER BY %s ASC LIMIT 100`, column, column, column),- lit.P{"project_id": projectId, "service": service, "type": profileType, "from": NewSQLiteTime(from), "to": NewSQLiteTime(to)})+ lit.P{"project_id": projectId, "service": service, "type": profileType, "from": sqlitetypes.NewSQLiteTime(from), "to": sqlitetypes.NewSQLiteTime(to)})if err != nil {return nil, err}@@ -560,7 +562,7 @@ func sqliteDimExpr(dimension string, params lit.P) (string, bool) {case "server_name":return "server_name", true}- key, ok := breakdownLabelKey(dimension)+ key, ok := shared.BreakdownLabelKey(dimension)if !ok || key == "" {return "", false}@@ -589,4 +591,10 @@ func sqliteLabelFilter(qualifier string, filters map[string]string, params lit.Preturn clause}-var ProfileRepository = profileRepository{}+var ProfileRepository = &profileRepository{}++func (r *profileRepository) DiscoverLabels(ctx context.Context, projectId uuid.UUID, service, profileType string, from, to time.Time, allowKeys []string) (map[string][]string, error) {+ return shared.DiscoverLabels(ctx, allowKeys, func(ctx context.Context, key string) ([]string, error) {+ return r.distinctLabelValues(ctx, projectId, service, profileType, key, from, to)+ })+}diff --git a/backend/app/repositories/session.repository_sqlite.go b/backend/app/repositories/telemetry/sqlite/session.repository.gosimilarity index 79%rename from backend/app/repositories/session.repository_sqlite.gorename to backend/app/repositories/telemetry/sqlite/session.repository.goindex 6d752c29..23beb28d 100644--- a/backend/app/repositories/session.repository_sqlite.go+++ b/backend/app/repositories/telemetry/sqlite/session.repository.go@@ -1,10 +1,12 @@-//go:build !pgch+//go:build !telemetry_ch && !telemetry_duckdb-package repositories+package sqliteimport ("context""fmt"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/shared"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/sqlitetypes""strings""time"@@ -15,16 +17,16 @@ import ()type sessionRow struct {- Id uuid.UUID `lit:"id"`- ProjectId uuid.UUID `lit:"project_id"`- StartedAt SQLiteTime `lit:"started_at"`- EndedAt *SQLiteTime `lit:"ended_at"`- Duration int64 `lit:"duration"`- ClientIP string `lit:"client_ip"`- Attributes SQLiteJSONMap `lit:"attributes"`- AppVersion string `lit:"app_version"`- ServerName string `lit:"server_name"`- DistributedTraceId *uuid.UUID `lit:"distributed_trace_id"`+ Id uuid.UUID `lit:"id"`+ ProjectId uuid.UUID `lit:"project_id"`+ StartedAt sqlitetypes.SQLiteTime `lit:"started_at"`+ EndedAt *sqlitetypes.SQLiteTime `lit:"ended_at"`+ Duration int64 `lit:"duration"`+ ClientIP string `lit:"client_ip"`+ Attributes sqlitetypes.SQLiteJSONMap `lit:"attributes"`+ AppVersion string `lit:"app_version"`+ ServerName string `lit:"server_name"`+ DistributedTraceId *uuid.UUID `lit:"distributed_trace_id"`}type sessionRowNaming struct{ lit.DefaultDbNamingStrategy }@@ -43,16 +45,16 @@ func sessionToRow(s models.Session) sessionRow {row := sessionRow{Id: s.Id,ProjectId: s.ProjectId,- StartedAt: NewSQLiteTime(s.StartedAt),+ StartedAt: sqlitetypes.NewSQLiteTime(s.StartedAt),Duration: s.Duration,ClientIP: s.ClientIP,- Attributes: NewSQLiteJSONMap(s.Attributes),+ Attributes: sqlitetypes.NewSQLiteJSONMap(s.Attributes),AppVersion: s.AppVersion,ServerName: s.ServerName,DistributedTraceId: s.DistributedTraceId,}if s.EndedAt != nil {- t := NewSQLiteTime(*s.EndedAt)+ t := sqlitetypes.NewSQLiteTime(*s.EndedAt)row.EndedAt = &t}return row@@ -133,7 +135,7 @@ func (r *sessionRepository) Upsert(ctx context.Context, sessions []models.Sessiofunc (r *sessionRepository) CountBetween(ctx context.Context, projectId uuid.UUID, start, end time.Time) (int64, error) {result, err := lit.SelectSingleNamed[models.CountResult](db.TelemetryDB,"SELECT count(*) as count FROM sessions WHERE project_id = :project_id AND started_at >= :start AND started_at <= :end",- lit.P{"project_id": projectId, "start": NewSQLiteTime(start), "end": NewSQLiteTime(end)})+ lit.P{"project_id": projectId, "start": sqlitetypes.NewSQLiteTime(start), "end": sqlitetypes.NewSQLiteTime(end)})if err != nil {return 0, err}@@ -143,14 +145,14 @@ func (r *sessionRepository) CountBetween(ctx context.Context, projectId uuid.UUIreturn int64(result.Count), nil}-func (r *sessionRepository) FindAll(ctx context.Context, projectId uuid.UUID, fromDate, toDate time.Time, page, pageSize int, orderBy string, sortDirection string, search string, attributeFilters []SessionAttributeFilter) ([]models.Session, int64, error) {+func (r *sessionRepository) FindAll(ctx context.Context, projectId uuid.UUID, fromDate, toDate time.Time, page, pageSize int, orderBy string, sortDirection string, search string, attributeFilters []shared.SessionAttributeFilter) ([]models.Session, int64, error) {whereExtra, extraParams := buildSessionFilterClauseSQLite(search, attributeFilters)countQuery := "SELECT count(*) as count FROM sessions WHERE project_id = :project_id AND started_at >= :start AND started_at <= :end" + whereExtracountParams := lit.P{"project_id": projectId,- "start": NewSQLiteTime(fromDate),- "end": NewSQLiteTime(toDate),+ "start": sqlitetypes.NewSQLiteTime(fromDate),+ "end": sqlitetypes.NewSQLiteTime(toDate),}for k, v := range extraParams {countParams[k] = v@@ -181,8 +183,8 @@ func (r *sessionRepository) FindAll(ctx context.Context, projectId uuid.UUID, frqueryParams := lit.P{"project_id": projectId,- "start": NewSQLiteTime(fromDate),- "end": NewSQLiteTime(toDate),+ "start": sqlitetypes.NewSQLiteTime(fromDate),+ "end": sqlitetypes.NewSQLiteTime(toDate),"limit": pageSize,"offset": offset,}@@ -205,7 +207,7 @@ func (r *sessionRepository) FindAll(ctx context.Context, projectId uuid.UUID, fr// mirroring the ClickHouse helper: search must be a valid UUID for an exact// id match (anything else is ignored), and each attribute filter becomes an// exact match against `json_extract(attributes, '$.<key>')`.-func buildSessionFilterClauseSQLite(search string, filters []SessionAttributeFilter) (string, lit.P) {+func buildSessionFilterClauseSQLite(search string, filters []shared.SessionAttributeFilter) (string, lit.P) {var sb strings.Builderparams := lit.P{}if s := strings.TrimSpace(search); s != "" {@@ -234,10 +236,10 @@ func (r *sessionRepository) FindById(ctx context.Context, projectId, sessionId uquery := "SELECT id, project_id, started_at, ended_at, duration, client_ip, attributes, app_version, server_name, distributed_trace_id FROM sessions WHERE project_id = :project_id AND id = :id"params := lit.P{"project_id": projectId, "id": sessionId}if startedAt != nil {- from, to := traceWindowBounds(*startedAt)+ from, to := shared.TraceWindowBounds(*startedAt)query += " AND started_at >= :from AND started_at <= :to"- params["from"] = NewSQLiteTime(from)- params["to"] = NewSQLiteTime(to)+ params["from"] = sqlitetypes.NewSQLiteTime(from)+ params["to"] = sqlitetypes.NewSQLiteTime(to)}query += " LIMIT 1"@@ -252,4 +254,4 @@ func (r *sessionRepository) FindById(ctx context.Context, projectId, sessionId ureturn &s, nil}-var SessionRepository = sessionRepository{}+var SessionRepository = &sessionRepository{}diff --git a/backend/app/repositories/session_recording.repository_sqlite.go b/backend/app/repositories/telemetry/sqlite/session_recording.repository.gosimilarity index 78%rename from backend/app/repositories/session_recording.repository_sqlite.gorename to backend/app/repositories/telemetry/sqlite/session_recording.repository.goindex 3b422d3a..0e412ac4 100644--- a/backend/app/repositories/session_recording.repository_sqlite.go+++ b/backend/app/repositories/telemetry/sqlite/session_recording.repository.go@@ -1,11 +1,12 @@-//go:build !pgch+//go:build !telemetry_ch && !telemetry_duckdb-package repositories+package sqliteimport ("context""database/sql""errors"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/sqlitetypes""github.com/google/uuid""github.com/tracewayapp/lit/v2"@@ -14,13 +15,13 @@ import ()type sessionRecording struct {- Id uuid.UUID `lit:"id"`- ProjectId uuid.UUID `lit:"project_id"`- ExceptionId uuid.UUID `lit:"exception_id"`- SessionId *uuid.UUID `lit:"session_id"`- SegmentIndex int32 `lit:"segment_index"`- FilePath string `lit:"file_path"`- RecordedAt SQLiteTime `lit:"recorded_at"`+ Id uuid.UUID `lit:"id"`+ ProjectId uuid.UUID `lit:"project_id"`+ ExceptionId uuid.UUID `lit:"exception_id"`+ SessionId *uuid.UUID `lit:"session_id"`+ SegmentIndex int32 `lit:"segment_index"`+ FilePath string `lit:"file_path"`+ RecordedAt sqlitetypes.SQLiteTime `lit:"recorded_at"`}func init() {@@ -50,7 +51,7 @@ func (r *sessionRecordingRepository) InsertAsync(ctx context.Context, recordingsSessionId: rec.SessionId,SegmentIndex: rec.SegmentIndex,FilePath: rec.FilePath,- RecordedAt: NewSQLiteTime(rec.RecordedAt),+ RecordedAt: sqlitetypes.NewSQLiteTime(rec.RecordedAt),}if err := lit.InsertExistingUuid(tx, &row); err != nil {return err@@ -61,7 +62,7 @@ func (r *sessionRecordingRepository) InsertAsync(ctx context.Context, recordings}func (r *sessionRecordingRepository) FindByExceptionId(ctx context.Context, projectId uuid.UUID, exceptionId uuid.UUID) (string, error) {- result, err := lit.SelectSingleNamed[filePathResult](db.TelemetryDB,+ result, err := lit.SelectSingleNamed[sqlitetypes.FilePathResult](db.TelemetryDB,"SELECT file_path FROM session_recordings WHERE project_id = :project_id AND exception_id = :exception_id ORDER BY recorded_at DESC LIMIT 1",lit.P{"project_id": projectId, "exception_id": exceptionId})if err != nil {@@ -100,4 +101,4 @@ func (r *sessionRecordingRepository) FindBySessionId(ctx context.Context, projec// Preserve original error contract: returns sql.ErrNoRows when not foundvar _ = errors.Is-var SessionRecordingRepository = sessionRecordingRepository{}+var SessionRecordingRepository = &sessionRecordingRepository{}diff --git a/backend/app/repositories/span.repository_sqlite.go b/backend/app/repositories/telemetry/sqlite/span.repository.gosimilarity index 66%rename from backend/app/repositories/span.repository_sqlite.gorename to backend/app/repositories/telemetry/sqlite/span.repository.goindex e5063b73..cab48342 100644--- a/backend/app/repositories/span.repository_sqlite.go+++ b/backend/app/repositories/telemetry/sqlite/span.repository.go@@ -1,9 +1,11 @@-//go:build !pgch+//go:build !telemetry_ch && !telemetry_duckdb-package repositories+package sqliteimport ("context"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/shared"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/sqlitetypes""time""github.com/google/uuid"@@ -13,15 +15,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"`- Attributes SQLiteJSONMap `lit:"attributes"`+ Id uuid.UUID `lit:"id"`+ TraceId uuid.UUID `lit:"trace_id"`+ ProjectId uuid.UUID `lit:"project_id"`+ Name string `lit:"name"`+ StartTime sqlitetypes.SQLiteTime `lit:"start_time"`+ Duration int64 `lit:"duration"`+ RecordedAt sqlitetypes.SQLiteTime `lit:"recorded_at"`+ ParentSpanId *uuid.UUID `lit:"parent_span_id"`+ Attributes sqlitetypes.SQLiteJSONMap `lit:"attributes"`}func init() {@@ -36,11 +38,11 @@ func spanToRow(s models.Span) span {TraceId: s.TraceId,ProjectId: s.ProjectId,Name: s.Name,- StartTime: NewSQLiteTime(s.StartTime),+ StartTime: sqlitetypes.NewSQLiteTime(s.StartTime),Duration: int64(s.Duration),- RecordedAt: NewSQLiteTime(s.RecordedAt),+ RecordedAt: sqlitetypes.NewSQLiteTime(s.RecordedAt),ParentSpanId: s.ParentSpanId,- Attributes: NewSQLiteJSONMap(s.Attributes),+ Attributes: sqlitetypes.NewSQLiteJSONMap(s.Attributes),}}@@ -90,10 +92,10 @@ func (r *spanRepository) FindByTraceId(ctx context.Context, projectId, traceId uWHERE project_id = :project_id AND trace_id = :trace_id`params := lit.P{"project_id": projectId, "trace_id": traceId}if recordedAt != nil {- from, to := traceWindowBounds(*recordedAt)+ from, to := shared.TraceWindowBounds(*recordedAt)query += ` AND recorded_at >= :from AND recorded_at <= :to`- params["from"] = NewSQLiteTime(from)- params["to"] = NewSQLiteTime(to)+ params["from"] = sqlitetypes.NewSQLiteTime(from)+ params["to"] = sqlitetypes.NewSQLiteTime(to)}query += ` ORDER BY start_time ASC`@@ -109,4 +111,4 @@ func (r *spanRepository) FindByTraceId(ctx context.Context, projectId, traceId ureturn spans, nil}-var SpanRepository = spanRepository{}+var SpanRepository = &spanRepository{}diff --git a/backend/app/repositories/task.repository_sqlite.go b/backend/app/repositories/telemetry/sqlite/task.repository.gosimilarity index 77%rename from backend/app/repositories/task.repository_sqlite.gorename to backend/app/repositories/telemetry/sqlite/task.repository.goindex c7462be4..0cb03841 100644--- a/backend/app/repositories/task.repository_sqlite.go+++ b/backend/app/repositories/telemetry/sqlite/task.repository.go@@ -1,10 +1,12 @@-//go:build !pgch+//go:build !telemetry_ch && !telemetry_duckdb-package repositories+package sqliteimport ("context""fmt"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/shared"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/sqlitetypes""sort""strings""time"@@ -16,18 +18,18 @@ import ()type task struct {- Id uuid.UUID `lit:"id"`- ProjectId uuid.UUID `lit:"project_id"`- TaskName string `lit:"task_name"`- Duration int64 `lit:"duration"`- RecordedAt SQLiteTime `lit:"recorded_at"`- ClientIP string `lit:"client_ip"`- Attributes SQLiteJSONMap `lit:"attributes"`- AppVersion string `lit:"app_version"`- ServerName string `lit:"server_name"`- DistributedTraceId *uuid.UUID `lit:"distributed_trace_id"`- SpanId *uuid.UUID `lit:"span_id"`- IsRoot bool `lit:"is_root"`+ Id uuid.UUID `lit:"id"`+ ProjectId uuid.UUID `lit:"project_id"`+ TaskName string `lit:"task_name"`+ Duration int64 `lit:"duration"`+ RecordedAt sqlitetypes.SQLiteTime `lit:"recorded_at"`+ ClientIP string `lit:"client_ip"`+ Attributes sqlitetypes.SQLiteJSONMap `lit:"attributes"`+ AppVersion string `lit:"app_version"`+ ServerName string `lit:"server_name"`+ DistributedTraceId *uuid.UUID `lit:"distributed_trace_id"`+ SpanId *uuid.UUID `lit:"span_id"`+ IsRoot bool `lit:"is_root"`}type taskGroupRow struct {@@ -40,8 +42,8 @@ type taskGroupRow struct {}type taskCountStatsRow struct {- Count int64 `lit:"count"`- AvgDurMs float64 `lit:"avg_dur_ms"`+ Count int64 `lit:"count"`+ AvgDurMs float64 `lit:"avg_dur_ms"`}type durationValueRow struct {@@ -63,9 +65,9 @@ func taskToRow(t models.Task) task {ProjectId: t.ProjectId,TaskName: t.TaskName,Duration: int64(t.Duration),- RecordedAt: NewSQLiteTime(t.RecordedAt),+ RecordedAt: sqlitetypes.NewSQLiteTime(t.RecordedAt),ClientIP: t.ClientIP,- Attributes: NewSQLiteJSONMap(t.Attributes),+ Attributes: sqlitetypes.NewSQLiteJSONMap(t.Attributes),AppVersion: t.AppVersion,ServerName: t.ServerName,DistributedTraceId: t.DistributedTraceId,@@ -120,7 +122,7 @@ func (e *taskRepository) InsertAsync(ctx context.Context, lines []models.Task) efunc (e *taskRepository) CountBetween(ctx context.Context, projectId uuid.UUID, start, end time.Time) (int64, error) {result, err := lit.SelectSingleNamed[models.CountResult](db.TelemetryDB,"SELECT COUNT(*) AS count FROM tasks WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to",- lit.P{"project_id": projectId, "from": NewSQLiteTime(start), "to": NewSQLiteTime(end)})+ lit.P{"project_id": projectId, "from": sqlitetypes.NewSQLiteTime(start), "to": sqlitetypes.NewSQLiteTime(end)})if err != nil {return 0, err}@@ -133,7 +135,7 @@ func (e *taskRepository) CountBetween(ctx context.Context, projectId uuid.UUID,func (e *taskRepository) FindAll(ctx context.Context, projectId uuid.UUID, fromDate, toDate time.Time, page, pageSize int, orderBy string) ([]models.Task, int64, error) {countResult, err := lit.SelectSingleNamed[models.CountResult](db.TelemetryDB,"SELECT COUNT(*) AS count FROM tasks WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to",- lit.P{"project_id": projectId, "from": NewSQLiteTime(fromDate), "to": NewSQLiteTime(toDate)})+ lit.P{"project_id": projectId, "from": sqlitetypes.NewSQLiteTime(fromDate), "to": sqlitetypes.NewSQLiteTime(toDate)})if err != nil {return nil, 0, err}@@ -153,7 +155,7 @@ func (e *taskRepository) FindAll(ctx context.Context, projectId uuid.UUID, fromDfmt.Sprintf(`SELECT id, project_id, task_name, duration, recorded_at, client_ip, attributes, app_version, server_name, distributed_trace_idFROM tasks WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :toORDER BY %s DESC LIMIT :limit OFFSET :offset`, orderBy),- lit.P{"project_id": projectId, "from": NewSQLiteTime(fromDate), "to": NewSQLiteTime(toDate), "limit": pageSize, "offset": offset})+ lit.P{"project_id": projectId, "from": sqlitetypes.NewSQLiteTime(fromDate), "to": sqlitetypes.NewSQLiteTime(toDate), "limit": pageSize, "offset": offset})if err != nil {return nil, 0, err}@@ -167,13 +169,13 @@ func (e *taskRepository) FindAll(ctx context.Context, projectId uuid.UUID, fromD}func (e *taskRepository) FindGroupedByTaskName(ctx context.Context, projectId uuid.UUID, fromDate, toDate time.Time, page, pageSize int, orderBy string, sortDirection string, search string, rootFilter string) ([]models.TaskStats, int64, error) {- params := lit.P{"project_id": projectId, "from": NewSQLiteTime(fromDate), "to": NewSQLiteTime(toDate)}+ params := lit.P{"project_id": projectId, "from": sqlitetypes.NewSQLiteTime(fromDate), "to": sqlitetypes.NewSQLiteTime(toDate)}whereClause := "project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to"if search != "" {whereClause += " AND INSTR(LOWER(task_name), LOWER(:search)) > 0"params["search"] = search}- whereClause += rootFilterClause("is_root", rootFilter)+ whereClause += shared.RootFilterClause("is_root", rootFilter)totalResult, err := lit.SelectSingleNamed[models.CountResult](db.TelemetryDB,"SELECT COUNT(DISTINCT task_name) AS count FROM tasks WHERE "+whereClause,@@ -196,7 +198,7 @@ func (e *taskRepository) FindGroupedByTaskName(ctx context.Context, projectId uuoffset := (page - 1) * pageSizevar baseQuery string- groupParams := lit.P{"project_id": projectId, "from": NewSQLiteTime(fromDate), "to": NewSQLiteTime(toDate)}+ groupParams := lit.P{"project_id": projectId, "from": sqlitetypes.NewSQLiteTime(fromDate), "to": sqlitetypes.NewSQLiteTime(toDate)}if search != "" {groupParams["search"] = search}@@ -237,8 +239,8 @@ func (e *taskRepository) FindGroupedByTaskName(ctx context.Context, projectId uustats = append(stats, models.TaskStats{TaskName: g.TaskName,Count: g.Count,- P50Duration: time.Duration(computePercentile(durations, 0.5)),- P95Duration: time.Duration(computePercentile(durations, 0.95)),+ P50Duration: time.Duration(shared.ComputePercentile(durations, 0.5)),+ P95Duration: time.Duration(shared.ComputePercentile(durations, 0.95)),AvgDuration: time.Duration(g.AvgDuration),LastSeen: ls,HasRoot: g.HasRoot,@@ -288,7 +290,7 @@ func (e *taskRepository) FindGroupedByTaskName(ctx context.Context, projectId uu}func (e *taskRepository) FindByTaskName(ctx context.Context, projectId uuid.UUID, taskName string, fromDate, toDate time.Time, page, pageSize int, orderBy string, sortDirection string) ([]models.Task, int64, error) {- params := lit.P{"project_id": projectId, "task_name": taskName, "from": NewSQLiteTime(fromDate), "to": NewSQLiteTime(toDate)}+ params := lit.P{"project_id": projectId, "task_name": taskName, "from": sqlitetypes.NewSQLiteTime(fromDate), "to": sqlitetypes.NewSQLiteTime(toDate)}countResult, err := lit.SelectSingleNamed[models.CountResult](db.TelemetryDB,"SELECT COUNT(*) AS count FROM tasks WHERE project_id = :project_id AND task_name = :task_name AND recorded_at >= :from AND recorded_at <= :to",@@ -317,7 +319,7 @@ func (e *taskRepository) FindByTaskName(ctx context.Context, projectId uuid.UUIDfmt.Sprintf(`SELECT id, project_id, task_name, duration, recorded_at, client_ip, attributes, app_version, server_name, distributed_trace_idFROM tasks WHERE project_id = :project_id AND task_name = :task_name AND recorded_at >= :from AND recorded_at <= :toORDER BY %s %s LIMIT :limit OFFSET :offset`, orderBy, sortDir),- lit.P{"project_id": projectId, "task_name": taskName, "from": NewSQLiteTime(fromDate), "to": NewSQLiteTime(toDate), "limit": pageSize, "offset": offset})+ lit.P{"project_id": projectId, "task_name": taskName, "from": sqlitetypes.NewSQLiteTime(fromDate), "to": sqlitetypes.NewSQLiteTime(toDate), "limit": pageSize, "offset": offset})if err != nil {return nil, 0, err}@@ -335,10 +337,10 @@ func (e *taskRepository) FindById(ctx context.Context, projectId, taskId uuid.UUFROM tasks WHERE project_id = :project_id AND id = :id`params := lit.P{"project_id": projectId, "id": taskId}if recordedAt != nil {- from, to := traceWindowBounds(*recordedAt)+ from, to := shared.TraceWindowBounds(*recordedAt)query += ` AND recorded_at >= :from AND recorded_at <= :to`- params["from"] = NewSQLiteTime(from)- params["to"] = NewSQLiteTime(to)+ params["from"] = sqlitetypes.NewSQLiteTime(from)+ params["to"] = sqlitetypes.NewSQLiteTime(to)}query += ` LIMIT 1`@@ -354,57 +356,57 @@ func (e *taskRepository) FindById(ctx context.Context, projectId, taskId uuid.UU}func (e *taskRepository) CountByHour(ctx context.Context, projectId uuid.UUID, start, end time.Time) ([]models.TimeSeriesPoint, error) {- results, err := lit.SelectNamed[timeSeriesResult](db.TelemetryDB,+ results, err := lit.SelectNamed[sqlitetypes.TimeSeriesResult](db.TelemetryDB,`SELECT strftime('%Y-%m-%d %H:00:00', recorded_at) as bucket, CAST(COUNT(*) AS REAL) as agg_valueFROM tasks WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :toGROUP BY bucket ORDER BY bucket ASC`,- lit.P{"project_id": projectId, "from": NewSQLiteTime(start), "to": NewSQLiteTime(end)})+ lit.P{"project_id": projectId, "from": sqlitetypes.NewSQLiteTime(start), "to": sqlitetypes.NewSQLiteTime(end)})if err != nil {return nil, err}- return timeSeriesResultsToPoints(results), nil+ return sqlitetypes.TimeSeriesResultsToPoints(results), nil}func (e *taskRepository) AvgDurationByHour(ctx context.Context, projectId uuid.UUID, start, end time.Time) ([]models.TimeSeriesPoint, error) {- results, err := lit.SelectNamed[timeSeriesResult](db.TelemetryDB,+ results, err := lit.SelectNamed[sqlitetypes.TimeSeriesResult](db.TelemetryDB,`SELECT strftime('%Y-%m-%d %H:00:00', recorded_at) as bucket, AVG(duration) / 1000000.0 as agg_valueFROM tasks WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :toGROUP BY bucket ORDER BY bucket ASC`,- lit.P{"project_id": projectId, "from": NewSQLiteTime(start), "to": NewSQLiteTime(end)})+ lit.P{"project_id": projectId, "from": sqlitetypes.NewSQLiteTime(start), "to": sqlitetypes.NewSQLiteTime(end)})if err != nil {return nil, err}- return timeSeriesResultsToPoints(results), nil+ return sqlitetypes.TimeSeriesResultsToPoints(results), nil}func (e *taskRepository) CountByInterval(ctx context.Context, projectId uuid.UUID, start, end time.Time, intervalMinutes int) ([]models.TimeSeriesPoint, error) {secs := intervalMinutes * 60- results, err := lit.SelectNamed[timeSeriesResult](db.TelemetryDB,+ results, err := lit.SelectNamed[sqlitetypes.TimeSeriesResult](db.TelemetryDB,fmt.Sprintf(`SELECT datetime((strftime('%%s', recorded_at) / %d) * %d, 'unixepoch') as bucket, CAST(COUNT(*) AS REAL) as agg_valueFROM tasks WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :toGROUP BY bucket ORDER BY bucket ASC`, secs, secs),- lit.P{"project_id": projectId, "from": NewSQLiteTime(start), "to": NewSQLiteTime(end)})+ lit.P{"project_id": projectId, "from": sqlitetypes.NewSQLiteTime(start), "to": sqlitetypes.NewSQLiteTime(end)})if err != nil {return nil, err}- return timeSeriesResultsToPoints(results), nil+ return sqlitetypes.TimeSeriesResultsToPoints(results), nil}func (e *taskRepository) AvgDurationByInterval(ctx context.Context, projectId uuid.UUID, start, end time.Time, intervalMinutes int) ([]models.TimeSeriesPoint, error) {secs := intervalMinutes * 60- results, err := lit.SelectNamed[timeSeriesResult](db.TelemetryDB,+ results, err := lit.SelectNamed[sqlitetypes.TimeSeriesResult](db.TelemetryDB,fmt.Sprintf(`SELECT datetime((strftime('%%s', recorded_at) / %d) * %d, 'unixepoch') as bucket, AVG(duration) / 1000000.0 as agg_valueFROM tasks WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :toGROUP BY bucket ORDER BY bucket ASC`, secs, secs),- lit.P{"project_id": projectId, "from": NewSQLiteTime(start), "to": NewSQLiteTime(end)})+ lit.P{"project_id": projectId, "from": sqlitetypes.NewSQLiteTime(start), "to": sqlitetypes.NewSQLiteTime(end)})if err != nil {return nil, err}- return timeSeriesResultsToPoints(results), nil+ return sqlitetypes.TimeSeriesResultsToPoints(results), nil}func (e *taskRepository) FindWorstTasks(ctx context.Context, projectId uuid.UUID, start, end time.Time, limit int) ([]models.TaskStats, error) {- params := lit.P{"project_id": projectId, "from": NewSQLiteTime(start), "to": NewSQLiteTime(end)}+ params := lit.P{"project_id": projectId, "from": sqlitetypes.NewSQLiteTime(start), "to": sqlitetypes.NewSQLiteTime(end)}groups, err := lit.SelectNamed[taskGroupRow](db.TelemetryDB,`SELECT task_name, COUNT(*) as count, AVG(duration) as avg_duration, MAX(recorded_at) as last_seen@@ -426,8 +428,8 @@ func (e *taskRepository) FindWorstTasks(ctx context.Context, projectId uuid.UUIDstats = append(stats, models.TaskStats{TaskName: g.TaskName,Count: g.Count,- P50Duration: time.Duration(computePercentile(durations, 0.5)),- P95Duration: time.Duration(computePercentile(durations, 0.95)),+ P50Duration: time.Duration(shared.ComputePercentile(durations, 0.5)),+ P95Duration: time.Duration(shared.ComputePercentile(durations, 0.95)),AvgDuration: time.Duration(g.AvgDuration),LastSeen: ls,})@@ -446,7 +448,7 @@ func (e *taskRepository) FindWorstTasks(ctx context.Context, projectId uuid.UUID}func (e *taskRepository) GetTaskStats(ctx context.Context, projectId uuid.UUID, taskName string, start, end time.Time) (*models.TaskDetailStats, error) {- params := lit.P{"project_id": projectId, "task_name": taskName, "from": NewSQLiteTime(start), "to": NewSQLiteTime(end)}+ params := lit.P{"project_id": projectId, "task_name": taskName, "from": sqlitetypes.NewSQLiteTime(start), "to": sqlitetypes.NewSQLiteTime(end)}durationMinutes := end.Sub(start).Minutes()if durationMinutes < 1 {@@ -454,7 +456,7 @@ func (e *taskRepository) GetTaskStats(ctx context.Context, projectId uuid.UUID,}statsRow, err := lit.SelectSingleNamed[taskCountStatsRow](db.TelemetryDB,- "SELECT COUNT(*) AS count, AVG(duration) / 1000000.0 AS avg_dur_ms FROM tasks WHERE project_id = :project_id AND task_name = :task_name AND recorded_at >= :from AND recorded_at <= :to",+ "SELECT COUNT(*) AS count, CASE WHEN COUNT(*) > 0 THEN AVG(duration) / 1000000.0 ELSE 0 END AS avg_dur_ms FROM tasks WHERE project_id = :project_id AND task_name = :task_name AND recorded_at >= :from AND recorded_at <= :to",params)if err != nil {return nil, err@@ -473,9 +475,9 @@ func (e *taskRepository) GetTaskStats(ctx context.Context, projectId uuid.UUID,return &models.TaskDetailStats{Count: statsRow.Count,AvgDuration: statsRow.AvgDurMs,- MedianDuration: computePercentile(durations, 0.5) / nsToMs,- P95Duration: computePercentile(durations, 0.95) / nsToMs,- P99Duration: computePercentile(durations, 0.99) / nsToMs,+ MedianDuration: shared.ComputePercentile(durations, 0.5) / nsToMs,+ P95Duration: shared.ComputePercentile(durations, 0.95) / nsToMs,+ P99Duration: shared.ComputePercentile(durations, 0.99) / nsToMs,Throughput: float64(statsRow.Count) / durationMinutes,}, nil}@@ -494,10 +496,10 @@ func (e *taskRepository) FindByDistributedTraceId(ctx context.Context, distributquery := `SELECT id, project_id, task_name, duration, recorded_at, client_ip, attributes, app_version, server_name, distributed_trace_idFROM tasks WHERE distributed_trace_id = :trace_id AND project_id IN (` + strings.Join(placeholders, ",") + `)`if recordedAt != nil {- from, to := distributedTraceWindowBounds(*recordedAt)+ from, to := shared.DistributedTraceWindowBounds(*recordedAt)query += ` AND recorded_at >= :from AND recorded_at <= :to`- params["from"] = NewSQLiteTime(from)- params["to"] = NewSQLiteTime(to)+ params["from"] = sqlitetypes.NewSQLiteTime(from)+ params["to"] = sqlitetypes.NewSQLiteTime(to)}query += ` ORDER BY recorded_at ASC`@@ -526,7 +528,7 @@ func (e *taskRepository) FindByDistributedTraceId(ctx context.Context, distributfunc fetchSortedTaskDurations(ctx context.Context, projectId uuid.UUID, taskName string, from, to time.Time) ([]float64, error) {results, err := lit.SelectNamed[durationValueRow](db.TelemetryDB,"SELECT duration FROM tasks WHERE project_id = :project_id AND task_name = :task_name AND recorded_at >= :from AND recorded_at <= :to ORDER BY duration ASC",- lit.P{"project_id": projectId, "task_name": taskName, "from": NewSQLiteTime(from), "to": NewSQLiteTime(to)})+ lit.P{"project_id": projectId, "task_name": taskName, "from": sqlitetypes.NewSQLiteTime(from), "to": sqlitetypes.NewSQLiteTime(to)})if err != nil {return nil, err}@@ -537,4 +539,4 @@ func fetchSortedTaskDurations(ctx context.Context, projectId uuid.UUID, taskNamereturn durations, nil}-var TaskRepository = taskRepository{}+var TaskRepository = &taskRepository{}diff --git a/backend/app/repositories/sqlite_types.go b/backend/app/repositories/telemetry/sqlitetypes/sqlitetypes.gosimilarity index 84%rename from backend/app/repositories/sqlite_types.gorename to backend/app/repositories/telemetry/sqlitetypes/sqlitetypes.goindex b3283af2..cd4392f3 100644--- a/backend/app/repositories/sqlite_types.go+++ b/backend/app/repositories/telemetry/sqlitetypes/sqlitetypes.go@@ -1,6 +1,4 @@-//go:build !pgch--package repositories+package sqlitetypesimport ("database/sql/driver"@@ -99,14 +97,14 @@ func (m SQLiteJSONMap) Value() (driver.Value, error) {return string(b), nil}-// timeSeriesResult is a generic result type for all time-bucketed aggregation queries.+// TimeSeriesResult is a generic result type for all time-bucketed aggregation queries.// Queries should alias the bucket as "bucket" and the value as "agg_value".-type timeSeriesResult struct {+type TimeSeriesResult struct {Bucket string `lit:"bucket"`Value float64 `lit:"agg_value"`}-func timeSeriesResultsToPoints(results []*timeSeriesResult) []models.TimeSeriesPoint {+func TimeSeriesResultsToPoints(results []*TimeSeriesResult) []models.TimeSeriesPoint {points := make([]models.TimeSeriesPoint, 0, len(results))for _, r := range results {t, _ := time.Parse("2006-01-02 15:04:05", r.Bucket)@@ -115,22 +113,22 @@ func timeSeriesResultsToPoints(results []*timeSeriesResult) []models.TimeSeriesPreturn points}-// groupedTimeSeriesResult is for time-bucketed queries with a group-by key.-type groupedTimeSeriesResult struct {+// GroupedTimeSeriesResult is for time-bucketed queries with a group-by key.+type GroupedTimeSeriesResult struct {Bucket string `lit:"bucket"`GroupKey *string `lit:"group_key"`Value float64 `lit:"agg_value"`}-// filePathResult is for single-column file_path queries.-type filePathResult struct {+// FilePathResult is for single-column file_path queries.+type FilePathResult struct {FilePath string `lit:"file_path"`}func init() {models.ExtensionModelRegistrations = append(models.ExtensionModelRegistrations, func(driver lit.Driver) {- lit.RegisterModel[timeSeriesResult](driver)- lit.RegisterModel[groupedTimeSeriesResult](driver)- lit.RegisterModel[filePathResult](driver)+ lit.RegisterModel[TimeSeriesResult](driver)+ lit.RegisterModel[GroupedTimeSeriesResult](driver)+ lit.RegisterModel[FilePathResult](driver)})}diff --git a/backend/app/repositories/task_repository_test.go b/backend/app/repositories/telemetry/task_repository_test.gosimilarity index 97%rename from backend/app/repositories/task_repository_test.gorename to backend/app/repositories/telemetry/task_repository_test.goindex cfe807c4..469de9e5 100644--- a/backend/app/repositories/task_repository_test.go+++ b/backend/app/repositories/telemetry/task_repository_test.go@@ -1,4 +1,4 @@-package repositories+package telemetryimport ("context"@@ -427,3 +427,17 @@ func TestTaskRepository_InsertEmpty(t *testing.T) {t.Fatalf("InsertAsync with empty slice should not error: %v", err)}}++func TestTaskRepository_GetTaskStats_EmptyWindow(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ now := time.Now().UTC()++ stats, err := TaskRepository.GetTaskStats(ctx, uuid.New(), "missing.task", now.Add(-time.Hour), now)+ if err != nil {+ t.Fatalf("GetTaskStats failed: %v", err)+ }+ if stats.Count != 0 {+ t.Errorf("expected count 0, got %d", stats.Count)+ }+}diff --git a/backend/app/repositories/telemetry/telemetry_ch.go b/backend/app/repositories/telemetry/telemetry_ch.gonew file mode 100644index 00000000..0d51cabd--- /dev/null+++ b/backend/app/repositories/telemetry/telemetry_ch.go@@ -0,0 +1,19 @@+//go:build telemetry_ch++package telemetry++import ch "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/clickhouse"++var (+ AiTraceRepository = ch.AiTraceRepository+ EndpointRepository = ch.EndpointRepository+ ExceptionStackTraceRepository = ch.ExceptionStackTraceRepository+ FiredNotificationRepository = ch.FiredNotificationRepository+ LogRecordRepository = ch.LogRecordRepository+ MetricPointRepository = ch.MetricPointRepository+ ProfileRepository = ch.ProfileRepository+ SessionRecordingRepository = ch.SessionRecordingRepository+ SessionRepository = ch.SessionRepository+ SpanRepository = ch.SpanRepository+ TaskRepository = ch.TaskRepository+)diff --git a/backend/app/repositories/telemetry/telemetry_duckdb.go b/backend/app/repositories/telemetry/telemetry_duckdb.gonew file mode 100644index 00000000..19473651--- /dev/null+++ b/backend/app/repositories/telemetry/telemetry_duckdb.go@@ -0,0 +1,19 @@+//go:build telemetry_duckdb++package telemetry++import duckdbrepo "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/duckdb"++var (+ AiTraceRepository = duckdbrepo.AiTraceRepository+ EndpointRepository = duckdbrepo.EndpointRepository+ ExceptionStackTraceRepository = duckdbrepo.ExceptionStackTraceRepository+ FiredNotificationRepository = duckdbrepo.FiredNotificationRepository+ LogRecordRepository = duckdbrepo.LogRecordRepository+ MetricPointRepository = duckdbrepo.MetricPointRepository+ ProfileRepository = duckdbrepo.ProfileRepository+ SessionRecordingRepository = duckdbrepo.SessionRecordingRepository+ SessionRepository = duckdbrepo.SessionRepository+ SpanRepository = duckdbrepo.SpanRepository+ TaskRepository = duckdbrepo.TaskRepository+)diff --git a/backend/app/repositories/telemetry/telemetry_shared.go b/backend/app/repositories/telemetry/telemetry_shared.gonew file mode 100644index 00000000..570a1126--- /dev/null+++ b/backend/app/repositories/telemetry/telemetry_shared.go@@ -0,0 +1,19 @@+package telemetry++import (+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/shared"+)++// Aliases and re-exports so consumers keep using the telemetry package+// regardless of which telemetry backend is compiled in.+type (+ SessionAttributeFilter = shared.SessionAttributeFilter+ FiredNotification = shared.FiredNotification+ LogAttributeFilter = shared.LogAttributeFilter+ LogSearchParams = shared.LogSearchParams+)++var (+ ComputeImpactReason = shared.ComputeImpactReason+ ComputeImpactScore = shared.ComputeImpactScore+)diff --git a/backend/app/repositories/telemetry/telemetry_sqlite.go b/backend/app/repositories/telemetry/telemetry_sqlite.gonew file mode 100644index 00000000..c83a8784--- /dev/null+++ b/backend/app/repositories/telemetry/telemetry_sqlite.go@@ -0,0 +1,19 @@+//go:build !telemetry_ch && !telemetry_duckdb++package telemetry++import sqliterepo "github.com/tracewayapp/traceway/backend/app/repositories/telemetry/sqlite"++var (+ AiTraceRepository = sqliterepo.AiTraceRepository+ EndpointRepository = sqliterepo.EndpointRepository+ ExceptionStackTraceRepository = sqliterepo.ExceptionStackTraceRepository+ FiredNotificationRepository = sqliterepo.FiredNotificationRepository+ LogRecordRepository = sqliterepo.LogRecordRepository+ MetricPointRepository = sqliterepo.MetricPointRepository+ ProfileRepository = sqliterepo.ProfileRepository+ SessionRecordingRepository = sqliterepo.SessionRecordingRepository+ SessionRepository = sqliterepo.SessionRepository+ SpanRepository = sqliterepo.SpanRepository+ TaskRepository = sqliterepo.TaskRepository+)diff --git a/backend/app/repositories/testhelper_clickhouse_test.go b/backend/app/repositories/telemetry/testhelper_clickhouse_test.gosimilarity index 98%rename from backend/app/repositories/testhelper_clickhouse_test.gorename to backend/app/repositories/telemetry/testhelper_clickhouse_test.goindex 1b3584eb..9f095e76 100644--- a/backend/app/repositories/testhelper_clickhouse_test.go+++ b/backend/app/repositories/telemetry/testhelper_clickhouse_test.go@@ -1,6 +1,6 @@-//go:build pgch+//go:build telemetry_ch-package repositories+package telemetryimport ("context"diff --git a/backend/app/repositories/telemetry/testhelper_duckdb_test.go b/backend/app/repositories/telemetry/testhelper_duckdb_test.gonew file mode 100644index 00000000..272c905e--- /dev/null+++ b/backend/app/repositories/telemetry/testhelper_duckdb_test.go@@ -0,0 +1,92 @@+//go:build telemetry_duckdb++package telemetry++import (+ "database/sql"+ "os"+ "path/filepath"+ "sort"+ "strings"+ "testing"++ "github.com/duckdb/duckdb-go/v2"+ "github.com/tracewayapp/lit/v2"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"+ _ "modernc.org/sqlite"+)++// setupTestDB mirrors the SQLite test harness but pairs an in-memory SQLite main+// DB with an in-memory DuckDB telemetry DB, so the shared telemetry test suite+// exercises the DuckDB repository implementations.+func setupTestDB(t *testing.T) {+ t.Helper()++ mainDB, err := sql.Open("sqlite", ":memory:")+ if err != nil {+ t.Fatalf("failed to open in-memory sqlite (main): %v", err)+ }+ mainDB.SetMaxOpenConns(1)+ if _, err := mainDB.Exec("PRAGMA foreign_keys = ON"); err != nil {+ t.Fatalf("failed to enable foreign keys: %v", err)+ }+ if _, err := mainDB.Exec("PRAGMA journal_mode = WAL"); err != nil {+ t.Fatalf("failed to set WAL mode: %v", err)+ }++ connector, err := duckdb.NewConnector("", nil)+ if err != nil {+ t.Fatalf("failed to open in-memory duckdb (telemetry): %v", err)+ }+ telemetryDB := sql.OpenDB(connector)++ db.DB = mainDB+ db.TelemetryDB = telemetryDB+ db.DuckDBConnector = connector+ db.Driver = lit.SQLite++ models.Init(db.Driver)++ if err := runDuckDBTelemetryMigrations(telemetryDB); err != nil {+ t.Fatalf("failed to run duckdb telemetry migrations: %v", err)+ }++ t.Cleanup(func() {+ mainDB.Close()+ telemetryDB.Close()+ })+}++func runDuckDBTelemetryMigrations(telemetryDB *sql.DB) error {+ // Apply every migration in order, like the production runner, so tests+ // keep seeing the full schema when migrations beyond 0001 are added.+ const dir = "../../migrations/duckdb_telemetry"+ entries, err := os.ReadDir(dir)+ if err != nil {+ return err+ }+ names := make([]string, 0, len(entries))+ for _, e := range entries {+ if !e.IsDir() && strings.HasSuffix(e.Name(), ".up.sql") {+ names = append(names, e.Name())+ }+ }+ sort.Strings(names)+ for _, name := range names {+ content, err := os.ReadFile(filepath.Join(dir, name))+ if err != nil {+ return err+ }+ for _, stmt := range strings.Split(string(content), ";") {+ stmt = strings.TrimSpace(stmt)+ if stmt == "" {+ continue+ }+ if _, err := telemetryDB.Exec(stmt); err != nil {+ return err+ }+ }+ }+ return nil+}diff --git a/backend/app/repositories/testhelper_sqlite_test.go b/backend/app/repositories/telemetry/testhelper_sqlite_test.gosimilarity index 99%rename from backend/app/repositories/testhelper_sqlite_test.gorename to backend/app/repositories/telemetry/testhelper_sqlite_test.goindex 832a4f3f..74c1e2db 100644--- a/backend/app/repositories/testhelper_sqlite_test.go+++ b/backend/app/repositories/telemetry/testhelper_sqlite_test.go@@ -1,6 +1,6 @@-//go:build !pgch+//go:build !telemetry_ch && !telemetry_duckdb-package repositories+package telemetryimport ("database/sql"diff --git a/backend/app/repositories/transactional/parity_test.go b/backend/app/repositories/transactional/parity_test.gonew file mode 100644index 00000000..5c7beae7--- /dev/null+++ b/backend/app/repositories/transactional/parity_test.go@@ -0,0 +1,75 @@+package transactional++import (+ "os"+ "path/filepath"+ "strings"+ "testing"+)++// The pg and sqlite backends are intentionally identical, dialect-neutral+// implementations (lit :name queries rendered per db.Driver); the build tag+// only selects which copy is compiled in. This test fails when a change lands+// in one copy but not the other, so the two backends cannot silently drift+// until a repository genuinely needs dialect-specific SQL — at which point the+// diverging file should be added to the exceptions list below with a comment+// explaining the divergence.+func TestPgAndSqliteBackendsStayInSync(t *testing.T) {+ exceptions := map[string]bool{}++ pgFiles := listGoFiles(t, "pg")+ sqliteFiles := listGoFiles(t, "sqlite")++ for name := range pgFiles {+ if !sqliteFiles[name] {+ t.Errorf("pg/%s has no sqlite/ counterpart", name)+ }+ }+ for name := range sqliteFiles {+ if !pgFiles[name] {+ t.Errorf("sqlite/%s has no pg/ counterpart", name)+ }+ }++ for name := range pgFiles {+ if !sqliteFiles[name] || exceptions[name] {+ continue+ }+ pgBody := normalizedBody(t, filepath.Join("pg", name))+ sqliteBody := normalizedBody(t, filepath.Join("sqlite", name))+ if pgBody != sqliteBody {+ t.Errorf("pg/%s and sqlite/%s differ beyond the build tag and package clause; apply the change to both copies or add the file to the exceptions list", name, name)+ }+ }+}++func listGoFiles(t *testing.T, dir string) map[string]bool {+ t.Helper()+ entries, err := os.ReadDir(dir)+ if err != nil {+ t.Fatalf("read %s: %v", dir, err)+ }+ files := map[string]bool{}+ for _, e := range entries {+ if !e.IsDir() && strings.HasSuffix(e.Name(), ".go") {+ files[e.Name()] = true+ }+ }+ return files+}++func normalizedBody(t *testing.T, path string) string {+ t.Helper()+ content, err := os.ReadFile(path)+ if err != nil {+ t.Fatalf("read %s: %v", path, err)+ }+ var kept []string+ for _, line := range strings.Split(string(content), "\n") {+ if strings.HasPrefix(line, "//go:build ") || strings.HasPrefix(line, "package ") {+ continue+ }+ kept = append(kept, line)+ }+ return strings.Join(kept, "\n")+}diff --git a/backend/app/repositories/authorization_code.repository.go b/backend/app/repositories/transactional/pg/authorization_code.repository.gosimilarity index 81%rename from backend/app/repositories/authorization_code.repository.gorename to backend/app/repositories/transactional/pg/authorization_code.repository.goindex 10df99f1..ccab2524 100644--- a/backend/app/repositories/authorization_code.repository.go+++ b/backend/app/repositories/transactional/pg/authorization_code.repository.go@@ -1,8 +1,11 @@-package repositories+//go:build transactional_pg++package pgimport ("database/sql""errors"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional/shared""time""github.com/tracewayapp/lit/v2"@@ -18,13 +21,13 @@ func (r *authorizationCodeRepository) Create(ex lit.Executor, code, clientId str`INSERT INTO authorization_codes (code_hash, client_id, user_id, redirect_uri, code_challenge, expires_at, created_at)VALUES (:hash, :client_id, :user_id, :redirect_uri, :code_challenge, :expires_at, :created_at)`,lit.P{- "hash": hashAuthToken(code),+ "hash": shared.HashAuthToken(code),"client_id": clientId,"user_id": userId,"redirect_uri": redirectUri,"code_challenge": codeChallenge,- "expires_at": formatAuthTime(expiresAt),- "created_at": formatAuthTime(time.Now()),+ "expires_at": shared.FormatAuthTime(expiresAt),+ "created_at": shared.FormatAuthTime(time.Now()),},)if err != nil {@@ -38,7 +41,7 @@ func (r *authorizationCodeRepository) FindByCode(ex lit.Executor, code string) (query, args, err := lit.ParseNamedQuery(db.Driver,"SELECT code_hash, client_id, user_id, redirect_uri, code_challenge, expires_at, created_at FROM authorization_codes WHERE code_hash = :hash",- lit.P{"hash": hashAuthToken(code)},+ lit.P{"hash": shared.HashAuthToken(code)},)if err != nil {return nil, err@@ -57,10 +60,10 @@ func (r *authorizationCodeRepository) FindByCode(ex lit.Executor, code string) (return nil, err}- if c.ExpiresAt, err = parseAuthTime(expiresAt); err != nil {+ if c.ExpiresAt, err = shared.ParseAuthTime(expiresAt); err != nil {return nil, err}- if c.CreatedAt, err = parseAuthTime(createdAt); err != nil {+ if c.CreatedAt, err = shared.ParseAuthTime(createdAt); err != nil {return nil, err}return &c, nil@@ -70,7 +73,7 @@ func (r *authorizationCodeRepository) Delete(ex lit.Executor, code string) (int6query, args, err := lit.ParseNamedQuery(db.Driver,"DELETE FROM authorization_codes WHERE code_hash = :hash",- lit.P{"hash": hashAuthToken(code)},+ lit.P{"hash": shared.HashAuthToken(code)},)if err != nil {return 0, err@@ -86,7 +89,7 @@ func (r *authorizationCodeRepository) PruneExpired(ex lit.Executor, now time.Timquery, args, err := lit.ParseNamedQuery(db.Driver,"DELETE FROM authorization_codes WHERE expires_at < :cutoff",- lit.P{"cutoff": formatAuthTime(now)},+ lit.P{"cutoff": shared.FormatAuthTime(now)},)if err != nil {return 0, errdiff --git a/backend/app/repositories/device_authorization.repository.go b/backend/app/repositories/transactional/pg/device_authorization.repository.gosimilarity index 84%rename from backend/app/repositories/device_authorization.repository.gorename to backend/app/repositories/transactional/pg/device_authorization.repository.goindex be22c54e..cddf7104 100644--- a/backend/app/repositories/device_authorization.repository.go+++ b/backend/app/repositories/transactional/pg/device_authorization.repository.go@@ -1,8 +1,11 @@-package repositories+//go:build transactional_pg++package pgimport ("database/sql""errors"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional/shared""strings""time"@@ -19,12 +22,12 @@ func (r *deviceAuthorizationRepository) Create(ex lit.Executor, deviceCode, user`INSERT INTO device_authorizations (device_code_hash, user_code, client_id, status, interval_seconds, expires_at, created_at)VALUES (:hash, :user_code, :client_id, 'pending', :interval, :expires_at, :created_at)`,lit.P{- "hash": hashAuthToken(deviceCode),+ "hash": shared.HashAuthToken(deviceCode),"user_code": userCode,"client_id": clientId,"interval": intervalSeconds,- "expires_at": formatAuthTime(expiresAt),- "created_at": formatAuthTime(time.Now()),+ "expires_at": shared.FormatAuthTime(expiresAt),+ "created_at": shared.FormatAuthTime(time.Now()),},)if err != nil {@@ -35,7 +38,7 @@ func (r *deviceAuthorizationRepository) Create(ex lit.Executor, deviceCode, user}func (r *deviceAuthorizationRepository) FindByDeviceCode(ex lit.Executor, deviceCode string) (*models.DeviceAuthorization, error) {- return r.findOne(ex, "device_code_hash = :v", hashAuthToken(deviceCode))+ return r.findOne(ex, "device_code_hash = :v", shared.HashAuthToken(deviceCode))}func (r *deviceAuthorizationRepository) FindByUserCode(ex lit.Executor, userCode string) (*models.DeviceAuthorization, error) {@@ -73,13 +76,13 @@ func (r *deviceAuthorizationRepository) findOne(ex lit.Executor, where, value stuid := int(userId.Int64)d.UserId = &uid}- if d.LastPolledAt, err = parseNullableAuthTime(lastPolled); err != nil {+ if d.LastPolledAt, err = shared.ParseNullableAuthTime(lastPolled); err != nil {return nil, err}- if d.ExpiresAt, err = parseAuthTime(expiresAt); err != nil {+ if d.ExpiresAt, err = shared.ParseAuthTime(expiresAt); err != nil {return nil, err}- if d.CreatedAt, err = parseAuthTime(createdAt); err != nil {+ if d.CreatedAt, err = shared.ParseAuthTime(createdAt); err != nil {return nil, err}return &d, nil@@ -117,7 +120,7 @@ func (r *deviceAuthorizationRepository) MarkPolled(ex lit.Executor, deviceCode squery, args, err := lit.ParseNamedQuery(db.Driver,"UPDATE device_authorizations SET last_polled_at = :polled, interval_seconds = :interval WHERE device_code_hash = :hash",- lit.P{"polled": formatAuthTime(polledAt), "interval": intervalSeconds, "hash": hashAuthToken(deviceCode)},+ lit.P{"polled": shared.FormatAuthTime(polledAt), "interval": intervalSeconds, "hash": shared.HashAuthToken(deviceCode)},)if err != nil {return err@@ -130,7 +133,7 @@ func (r *deviceAuthorizationRepository) Delete(ex lit.Executor, deviceCode strinquery, args, err := lit.ParseNamedQuery(db.Driver,"DELETE FROM device_authorizations WHERE device_code_hash = :hash",- lit.P{"hash": hashAuthToken(deviceCode)},+ lit.P{"hash": shared.HashAuthToken(deviceCode)},)if err != nil {return 0, err@@ -146,7 +149,7 @@ func (r *deviceAuthorizationRepository) PruneExpired(ex lit.Executor, now time.Tquery, args, err := lit.ParseNamedQuery(db.Driver,"DELETE FROM device_authorizations WHERE expires_at < :cutoff",- lit.P{"cutoff": formatAuthTime(now)},+ lit.P{"cutoff": shared.FormatAuthTime(now)},)if err != nil {return 0, errdiff --git a/backend/app/repositories/invitation.repository.go b/backend/app/repositories/transactional/pg/invitation.repository.gosimilarity index 98%rename from backend/app/repositories/invitation.repository.gorename to backend/app/repositories/transactional/pg/invitation.repository.goindex 409ae537..56642b38 100644--- a/backend/app/repositories/invitation.repository.go+++ b/backend/app/repositories/transactional/pg/invitation.repository.go@@ -1,4 +1,6 @@-package repositories+//go:build transactional_pg++package pgimport ("database/sql"diff --git a/backend/app/repositories/metric_registry.repository.go b/backend/app/repositories/transactional/pg/metric_registry.repository.gosimilarity index 93%rename from backend/app/repositories/metric_registry.repository.gorename to backend/app/repositories/transactional/pg/metric_registry.repository.goindex e1556449..e2fcb6fa 100644--- a/backend/app/repositories/metric_registry.repository.go+++ b/backend/app/repositories/transactional/pg/metric_registry.repository.go@@ -1,7 +1,10 @@-package repositories+//go:build transactional_pg++package pgimport ("database/sql"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional/shared""sync""time"@@ -72,13 +75,7 @@ func (r *metricRegistryRepository) Update(tx *sql.Tx, entry *models.MetricRegistreturn lit.UpdateNamed(tx, entry, "id = :id", lit.P{"id": entry.Id})}-type MetricRegistrationEntry struct {- Name string- Unit string- MetricType string-}--func (r *metricRegistryRepository) EnsureRegisteredWithUnits(tx *sql.Tx, projectId uuid.UUID, entries []MetricRegistrationEntry) error {+func (r *metricRegistryRepository) EnsureRegisteredWithUnits(tx *sql.Tx, projectId uuid.UUID, entries []shared.MetricRegistrationEntry) error {for _, entry := range entries {key := projectId.String() + ":" + entry.Nameif _, loaded := r.knownMetrics.Load(key); loaded {@@ -158,4 +155,4 @@ func (r *metricRegistryRepository) KnownCount() int {return count}-var MetricRegistryRepository = metricRegistryRepository{}+var MetricRegistryRepository = &metricRegistryRepository{}diff --git a/backend/app/repositories/notification_channel.repository.go b/backend/app/repositories/transactional/pg/notification_channel.repository.gosimilarity index 98%rename from backend/app/repositories/notification_channel.repository.gorename to backend/app/repositories/transactional/pg/notification_channel.repository.goindex d56c72e1..1cf6d1d4 100644--- a/backend/app/repositories/notification_channel.repository.go+++ b/backend/app/repositories/transactional/pg/notification_channel.repository.go@@ -1,4 +1,6 @@-package repositories+//go:build transactional_pg++package pgimport ("database/sql"diff --git a/backend/app/repositories/notification_rule.repository.go b/backend/app/repositories/transactional/pg/notification_rule.repository.gosimilarity index 99%rename from backend/app/repositories/notification_rule.repository.gorename to backend/app/repositories/transactional/pg/notification_rule.repository.goindex f3063b45..0923b4b0 100644--- a/backend/app/repositories/notification_rule.repository.go+++ b/backend/app/repositories/transactional/pg/notification_rule.repository.go@@ -1,4 +1,6 @@-package repositories+//go:build transactional_pg++package pgimport ("database/sql"diff --git a/backend/app/repositories/oauth_client.repository.go b/backend/app/repositories/transactional/pg/oauth_client.repository.gosimilarity index 86%rename from backend/app/repositories/oauth_client.repository.gorename to backend/app/repositories/transactional/pg/oauth_client.repository.goindex 6cbc88e5..e33f3575 100644--- a/backend/app/repositories/oauth_client.repository.go+++ b/backend/app/repositories/transactional/pg/oauth_client.repository.go@@ -1,9 +1,12 @@-package repositories+//go:build transactional_pg++package pgimport ("database/sql""encoding/json""errors"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional/shared""time""github.com/tracewayapp/lit/v2"@@ -26,7 +29,7 @@ func (r *oauthClientRepository) Create(ex lit.Executor, client *models.OauthClie"id": client.Id,"name": client.Name,"redirect_uris": string(uris),- "created_at": formatAuthTime(client.CreatedAt),+ "created_at": shared.FormatAuthTime(client.CreatedAt),},)if err != nil {@@ -62,7 +65,7 @@ func (r *oauthClientRepository) FindById(ex lit.Executor, id string) (*models.Oaif err := json.Unmarshal([]byte(uris), &c.RedirectUris); err != nil {return nil, err}- if c.CreatedAt, err = parseAuthTime(createdAt); err != nil {+ if c.CreatedAt, err = shared.ParseAuthTime(createdAt); err != nil {return nil, err}return &c, nil@@ -76,7 +79,7 @@ func (r *oauthClientRepository) PruneStale(ex lit.Executor, now time.Time) (int6`DELETE FROM oauth_clients WHERE created_at < :cutoffAND NOT EXISTS (SELECT 1 FROM refresh_tokens WHERE refresh_tokens.client_id = oauth_clients.id)AND NOT EXISTS (SELECT 1 FROM authorization_codes WHERE authorization_codes.client_id = oauth_clients.id)`,- lit.P{"cutoff": formatAuthTime(now.Add(-staleOauthClientRetention))},+ lit.P{"cutoff": shared.FormatAuthTime(now.Add(-staleOauthClientRetention))},)if err != nil {return 0, errdiff --git a/backend/app/repositories/oauth_session.repository.go b/backend/app/repositories/transactional/pg/oauth_session.repository.gosimilarity index 98%rename from backend/app/repositories/oauth_session.repository.gorename to backend/app/repositories/transactional/pg/oauth_session.repository.goindex ecf446cd..44ff9074 100644--- a/backend/app/repositories/oauth_session.repository.go+++ b/backend/app/repositories/transactional/pg/oauth_session.repository.go@@ -1,4 +1,6 @@-package repositories+//go:build transactional_pg++package pgimport ("database/sql"diff --git a/backend/app/repositories/organization.repository.go b/backend/app/repositories/transactional/pg/organization.repository.gosimilarity index 99%rename from backend/app/repositories/organization.repository.gorename to backend/app/repositories/transactional/pg/organization.repository.goindex c239eb67..4306bb5a 100644--- a/backend/app/repositories/organization.repository.go+++ b/backend/app/repositories/transactional/pg/organization.repository.go@@ -1,4 +1,6 @@-package repositories+//go:build transactional_pg++package pgimport ("database/sql"diff --git a/backend/app/repositories/personal_access_token.repository.go b/backend/app/repositories/transactional/pg/personal_access_token.repository.gosimilarity index 83%rename from backend/app/repositories/personal_access_token.repository.gorename to backend/app/repositories/transactional/pg/personal_access_token.repository.goindex c4ba37e3..b0a71996 100644--- a/backend/app/repositories/personal_access_token.repository.go+++ b/backend/app/repositories/transactional/pg/personal_access_token.repository.go@@ -1,8 +1,11 @@-package repositories+//go:build transactional_pg++package pgimport ("database/sql""errors"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional/shared""time""github.com/tracewayapp/lit/v2"@@ -10,19 +13,12 @@ import ("github.com/tracewayapp/traceway/backend/app/models")-type ActivePAT struct {- Id string- UserId int- Email string- LastUsedAt *time.Time-}-type personalAccessTokenRepository struct{}func (r *personalAccessTokenRepository) Create(ex lit.Executor, id, token, prefix string, userId int, name string, expiresAt *time.Time) error {var expires anyif expiresAt != nil {- expires = formatAuthTime(*expiresAt)+ expires = shared.FormatAuthTime(*expiresAt)}query, args, err := lit.ParseNamedQuery(db.Driver,@@ -30,13 +26,13 @@ func (r *personalAccessTokenRepository) Create(ex lit.Executor, id, token, prefiVALUES (:id, :hash, :prefix, :user_id, :name, :revoked, :expires_at, :created_at)`,lit.P{"id": id,- "hash": hashAuthToken(token),+ "hash": shared.HashAuthToken(token),"prefix": prefix,"user_id": userId,"name": name,"revoked": false,"expires_at": expires,- "created_at": formatAuthTime(time.Now()),+ "created_at": shared.FormatAuthTime(time.Now()),},)if err != nil {@@ -46,21 +42,21 @@ func (r *personalAccessTokenRepository) Create(ex lit.Executor, id, token, prefireturn err}-func (r *personalAccessTokenRepository) FindActiveByToken(ex lit.Executor, token string) (*ActivePAT, error) {+func (r *personalAccessTokenRepository) FindActiveByToken(ex lit.Executor, token string) (*shared.ActivePAT, error) {query, args, err := lit.ParseNamedQuery(db.Driver,`SELECT p.id, p.user_id, p.revoked, p.expires_at, p.last_used_at, u.emailFROM personal_access_tokens pJOIN users u ON u.id = p.user_idWHERE p.token_hash = :hash`,- lit.P{"hash": hashAuthToken(token)},+ lit.P{"hash": shared.HashAuthToken(token)},)if err != nil {return nil, err}var (- pat ActivePAT+ pat shared.ActivePATrevoked boolexpiresAt sql.NullStringlastUsed sql.NullString@@ -76,14 +72,14 @@ func (r *personalAccessTokenRepository) FindActiveByToken(ex lit.Executor, tokenif revoked {return nil, nil}- expiry, err := parseNullableAuthTime(expiresAt)+ expiry, err := shared.ParseNullableAuthTime(expiresAt)if err != nil {return nil, err}if expiry != nil && time.Now().After(*expiry) {return nil, nil}- if pat.LastUsedAt, err = parseNullableAuthTime(lastUsed); err != nil {+ if pat.LastUsedAt, err = shared.ParseNullableAuthTime(lastUsed); err != nil {return nil, err}return &pat, nil@@ -119,13 +115,13 @@ func (r *personalAccessTokenRepository) ListByUser(ex lit.Executor, userId int)if err := rows.Scan(&pat.Id, &pat.Prefix, &pat.Name, &lastUsed, &expiresAt, &createdAt); err != nil {return nil, err}- if pat.LastUsedAt, err = parseNullableAuthTime(lastUsed); err != nil {+ if pat.LastUsedAt, err = shared.ParseNullableAuthTime(lastUsed); err != nil {return nil, err}- if pat.ExpiresAt, err = parseNullableAuthTime(expiresAt); err != nil {+ if pat.ExpiresAt, err = shared.ParseNullableAuthTime(expiresAt); err != nil {return nil, err}- if pat.CreatedAt, err = parseAuthTime(createdAt); err != nil {+ if pat.CreatedAt, err = shared.ParseAuthTime(createdAt); err != nil {return nil, err}tokens = append(tokens, &pat)@@ -157,7 +153,7 @@ func (r *personalAccessTokenRepository) PruneExpired(ex lit.Executor, now time.Tquery, args, err := lit.ParseNamedQuery(db.Driver,"DELETE FROM personal_access_tokens WHERE revoked = :revoked OR (expires_at IS NOT NULL AND expires_at < :cutoff)",- lit.P{"revoked": true, "cutoff": formatAuthTime(now)},+ lit.P{"revoked": true, "cutoff": shared.FormatAuthTime(now)},)if err != nil {return 0, err@@ -173,7 +169,7 @@ func (r *personalAccessTokenRepository) TouchLastUsed(ex lit.Executor, id stringquery, args, err := lit.ParseNamedQuery(db.Driver,"UPDATE personal_access_tokens SET last_used_at = :used WHERE id = :id",- lit.P{"used": formatAuthTime(usedAt), "id": id},+ lit.P{"used": shared.FormatAuthTime(usedAt), "id": id},)if err != nil {return errdiff --git a/backend/app/repositories/project.repository.go b/backend/app/repositories/transactional/pg/project.repository.gosimilarity index 96%rename from backend/app/repositories/project.repository.gorename to backend/app/repositories/transactional/pg/project.repository.goindex cbbc65ed..04149389 100644--- a/backend/app/repositories/project.repository.go+++ b/backend/app/repositories/transactional/pg/project.repository.go@@ -1,4 +1,6 @@-package repositories+//go:build transactional_pg++package pgimport ("database/sql"@@ -6,6 +8,7 @@ import ("strings""time"+ "github.com/tracewayapp/traceway/backend/app/db""github.com/tracewayapp/traceway/backend/app/models""github.com/google/uuid"@@ -233,11 +236,11 @@ func (p *projectRepository) Delete(tx *sql.Tx, id uuid.UUID) error {"metric_registry",}for _, table := range related {- if err := lit.Delete(tx, "DELETE FROM "+table+" WHERE project_id = $1", id); err != nil {+ if err := lit.DeleteNamed(db.Driver, tx, "DELETE FROM "+table+" WHERE project_id = :project_id", lit.P{"project_id": id}); err != nil {return fmt.Errorf("deleting %s: %w", table, err)}}- return lit.Delete(tx, "DELETE FROM projects WHERE id = $1", id)+ return lit.DeleteNamed(db.Driver, tx, "DELETE FROM projects WHERE id = :id", lit.P{"id": id})}func (p *projectRepository) FindBySourceMapToken(tx *sql.Tx, token string) (*models.Project, error) {diff --git a/backend/app/repositories/refresh_token.repository.go b/backend/app/repositories/transactional/pg/refresh_token.repository.gosimilarity index 83%rename from backend/app/repositories/refresh_token.repository.gorename to backend/app/repositories/transactional/pg/refresh_token.repository.goindex ef733ea5..61bdd5ad 100644--- a/backend/app/repositories/refresh_token.repository.go+++ b/backend/app/repositories/transactional/pg/refresh_token.repository.go@@ -1,8 +1,11 @@-package repositories+//go:build transactional_pg++package pgimport ("database/sql""errors"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional/shared""time""github.com/tracewayapp/lit/v2"@@ -18,14 +21,14 @@ func (r *refreshTokenRepository) Insert(ex lit.Executor, token, familyId string,`INSERT INTO refresh_tokens (token_hash, family_id, user_id, client_id, revoked, used, expires_at, created_at)VALUES (:hash, :family, :user_id, :client_id, :revoked, :used, :expires_at, :created_at)`,lit.P{- "hash": hashAuthToken(token),+ "hash": shared.HashAuthToken(token),"family": familyId,"user_id": userId,"client_id": clientId,"revoked": false,"used": false,- "expires_at": formatAuthTime(expiresAt),- "created_at": formatAuthTime(time.Now()),+ "expires_at": shared.FormatAuthTime(expiresAt),+ "created_at": shared.FormatAuthTime(time.Now()),},)if err != nil {@@ -39,7 +42,7 @@ func (r *refreshTokenRepository) FindByToken(ex lit.Executor, token string) (*moquery, args, err := lit.ParseNamedQuery(db.Driver,"SELECT token_hash, family_id, user_id, client_id, revoked, used, used_at, expires_at, created_at FROM refresh_tokens WHERE token_hash = :hash",- lit.P{"hash": hashAuthToken(token)},+ lit.P{"hash": shared.HashAuthToken(token)},)if err != nil {return nil, err@@ -59,13 +62,13 @@ func (r *refreshTokenRepository) FindByToken(ex lit.Executor, token string) (*moreturn nil, err}- if t.UsedAt, err = parseNullableAuthTime(usedAt); err != nil {+ if t.UsedAt, err = shared.ParseNullableAuthTime(usedAt); err != nil {return nil, err}- if t.ExpiresAt, err = parseAuthTime(expiresAt); err != nil {+ if t.ExpiresAt, err = shared.ParseAuthTime(expiresAt); err != nil {return nil, err}- if t.CreatedAt, err = parseAuthTime(createdAt); err != nil {+ if t.CreatedAt, err = shared.ParseAuthTime(createdAt); err != nil {return nil, err}return &t, nil@@ -80,7 +83,7 @@ func (r *refreshTokenRepository) MarkUsedIfUnused(ex lit.Executor, token string,query, args, err := lit.ParseNamedQuery(db.Driver,"UPDATE refresh_tokens SET used = :used, used_at = :used_at WHERE token_hash = :hash AND used = :active AND revoked = :active",- lit.P{"used": true, "used_at": formatAuthTime(usedAt), "hash": hashAuthToken(token), "active": false},+ lit.P{"used": true, "used_at": shared.FormatAuthTime(usedAt), "hash": shared.HashAuthToken(token), "active": false},)if err != nil {return 0, err@@ -119,10 +122,10 @@ func (r *refreshTokenRepository) PruneExpired(ex lit.Executor, now time.Time) (idb.Driver,"DELETE FROM refresh_tokens WHERE expires_at < :cutoff OR revoked = :revoked OR (used = :used AND used_at < :used_cutoff)",lit.P{- "cutoff": formatAuthTime(now),+ "cutoff": shared.FormatAuthTime(now),"revoked": true,"used": true,- "used_cutoff": formatAuthTime(now.Add(-usedRefreshTokenRetention)),+ "used_cutoff": shared.FormatAuthTime(now.Add(-usedRefreshTokenRetention)),},)if err != nil {diff --git a/backend/app/repositories/user.repository.go b/backend/app/repositories/transactional/pg/user.repository.gosimilarity index 99%rename from backend/app/repositories/user.repository.gorename to backend/app/repositories/transactional/pg/user.repository.goindex 613d28c7..735e5df0 100644--- a/backend/app/repositories/user.repository.go+++ b/backend/app/repositories/transactional/pg/user.repository.go@@ -1,4 +1,6 @@-package repositories+//go:build transactional_pg++package pgimport ("database/sql"diff --git a/backend/app/repositories/widget_group.repository.go b/backend/app/repositories/transactional/pg/widget_group.repository.gosimilarity index 99%rename from backend/app/repositories/widget_group.repository.gorename to backend/app/repositories/transactional/pg/widget_group.repository.goindex 0e22a440..7f4848eb 100644--- a/backend/app/repositories/widget_group.repository.go+++ b/backend/app/repositories/transactional/pg/widget_group.repository.go@@ -1,4 +1,6 @@-package repositories+//go:build transactional_pg++package pgimport ("database/sql"diff --git a/backend/app/repositories/project.repository_sqlite_test.go b/backend/app/repositories/transactional/project.repository_test.gosimilarity index 98%rename from backend/app/repositories/project.repository_sqlite_test.gorename to backend/app/repositories/transactional/project.repository_test.goindex f3daf301..0fa2b428 100644--- a/backend/app/repositories/project.repository_sqlite_test.go+++ b/backend/app/repositories/transactional/project.repository_test.go@@ -1,6 +1,6 @@-//go:build !pgch+//go:build !transactional_pg-package repositories+package transactionalimport ("testing"diff --git a/backend/app/repositories/transactional/shared/auth_tokens.go b/backend/app/repositories/transactional/shared/auth_tokens.gonew file mode 100644index 00000000..c4dd7b74--- /dev/null+++ b/backend/app/repositories/transactional/shared/auth_tokens.go@@ -0,0 +1,44 @@+package shared++import (+ "crypto/sha256"+ "database/sql"+ "encoding/hex"+ "fmt"+ "time"+)++// AuthTimeLayout is the canonical storage format for auth-token timestamps.+// It is shared by every transactional backend so hashes and times written by+// one backend stay readable after switching to another.+const AuthTimeLayout = "2006-01-02T15:04:05.000000000Z07:00"++func HashAuthToken(plaintext string) string {+ sum := sha256.Sum256([]byte(plaintext))+ return hex.EncodeToString(sum[:])+}++func FormatAuthTime(t time.Time) string {+ return t.UTC().Format(AuthTimeLayout)+}++func ParseAuthTime(s string) (time.Time, error) {+ layouts := []string{AuthTimeLayout, time.RFC3339Nano, time.RFC3339, "2006-01-02 15:04:05.999999999-07:00", "2006-01-02 15:04:05"}+ for _, layout := range layouts {+ if parsed, err := time.Parse(layout, s); err == nil {+ return parsed.UTC(), nil+ }+ }+ return time.Time{}, fmt.Errorf("auth: cannot parse time %q", s)+}++func ParseNullableAuthTime(ns sql.NullString) (*time.Time, error) {+ if !ns.Valid || ns.String == "" {+ return nil, nil+ }+ t, err := ParseAuthTime(ns.String)+ if err != nil {+ return nil, err+ }+ return &t, nil+}diff --git a/backend/app/repositories/transactional/shared/types.go b/backend/app/repositories/transactional/shared/types.gonew file mode 100644index 00000000..b0701993--- /dev/null+++ b/backend/app/repositories/transactional/shared/types.go@@ -0,0 +1,19 @@+package shared++import "time"++// Types that cross the transactional facade boundary, defined once so every+// backend returns the same shapes to consumers.++type MetricRegistrationEntry struct {+ Name string+ Unit string+ MetricType string+}++type ActivePAT struct {+ Id string+ UserId int+ Email string+ LastUsedAt *time.Time+}diff --git a/backend/app/repositories/transactional/sqlite/authorization_code.repository.go b/backend/app/repositories/transactional/sqlite/authorization_code.repository.gonew file mode 100644index 00000000..34ee22d0--- /dev/null+++ b/backend/app/repositories/transactional/sqlite/authorization_code.repository.go@@ -0,0 +1,104 @@+//go:build !transactional_pg++package sqlite++import (+ "database/sql"+ "errors"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional/shared"+ "time"++ "github.com/tracewayapp/lit/v2"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"+)++type authorizationCodeRepository struct{}++func (r *authorizationCodeRepository) Create(ex lit.Executor, code, clientId string, userId int, redirectUri, codeChallenge string, expiresAt time.Time) error {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ `INSERT INTO authorization_codes (code_hash, client_id, user_id, redirect_uri, code_challenge, expires_at, created_at)+ VALUES (:hash, :client_id, :user_id, :redirect_uri, :code_challenge, :expires_at, :created_at)`,+ lit.P{+ "hash": shared.HashAuthToken(code),+ "client_id": clientId,+ "user_id": userId,+ "redirect_uri": redirectUri,+ "code_challenge": codeChallenge,+ "expires_at": shared.FormatAuthTime(expiresAt),+ "created_at": shared.FormatAuthTime(time.Now()),+ },+ )+ if err != nil {+ return err+ }+ _, err = ex.Exec(query, args...)+ return err+}++func (r *authorizationCodeRepository) FindByCode(ex lit.Executor, code string) (*models.AuthorizationCode, error) {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ "SELECT code_hash, client_id, user_id, redirect_uri, code_challenge, expires_at, created_at FROM authorization_codes WHERE code_hash = :hash",+ lit.P{"hash": shared.HashAuthToken(code)},+ )+ if err != nil {+ return nil, err+ }++ var (+ c models.AuthorizationCode+ expiresAt string+ createdAt string+ )+ err = ex.QueryRow(query, args...).Scan(&c.CodeHash, &c.ClientId, &c.UserId, &c.RedirectUri, &c.CodeChallenge, &expiresAt, &createdAt)+ if errors.Is(err, sql.ErrNoRows) {+ return nil, nil+ }+ if err != nil {+ return nil, err+ }++ if c.ExpiresAt, err = shared.ParseAuthTime(expiresAt); err != nil {+ return nil, err+ }+ if c.CreatedAt, err = shared.ParseAuthTime(createdAt); err != nil {+ return nil, err+ }+ return &c, nil+}++func (r *authorizationCodeRepository) Delete(ex lit.Executor, code string) (int64, error) {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ "DELETE FROM authorization_codes WHERE code_hash = :hash",+ lit.P{"hash": shared.HashAuthToken(code)},+ )+ if err != nil {+ return 0, err+ }+ res, err := ex.Exec(query, args...)+ if err != nil {+ return 0, err+ }+ return res.RowsAffected()+}++func (r *authorizationCodeRepository) PruneExpired(ex lit.Executor, now time.Time) (int64, error) {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ "DELETE FROM authorization_codes WHERE expires_at < :cutoff",+ lit.P{"cutoff": shared.FormatAuthTime(now)},+ )+ if err != nil {+ return 0, err+ }+ res, err := ex.Exec(query, args...)+ if err != nil {+ return 0, err+ }+ return res.RowsAffected()+}++var AuthorizationCodeRepository = authorizationCodeRepository{}diff --git a/backend/app/repositories/transactional/sqlite/device_authorization.repository.go b/backend/app/repositories/transactional/sqlite/device_authorization.repository.gonew file mode 100644index 00000000..f57097db--- /dev/null+++ b/backend/app/repositories/transactional/sqlite/device_authorization.repository.go@@ -0,0 +1,164 @@+//go:build !transactional_pg++package sqlite++import (+ "database/sql"+ "errors"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional/shared"+ "strings"+ "time"++ "github.com/tracewayapp/lit/v2"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"+)++type deviceAuthorizationRepository struct{}++func (r *deviceAuthorizationRepository) Create(ex lit.Executor, deviceCode, userCode, clientId string, intervalSeconds int, expiresAt time.Time) error {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ `INSERT INTO device_authorizations (device_code_hash, user_code, client_id, status, interval_seconds, expires_at, created_at)+ VALUES (:hash, :user_code, :client_id, 'pending', :interval, :expires_at, :created_at)`,+ lit.P{+ "hash": shared.HashAuthToken(deviceCode),+ "user_code": userCode,+ "client_id": clientId,+ "interval": intervalSeconds,+ "expires_at": shared.FormatAuthTime(expiresAt),+ "created_at": shared.FormatAuthTime(time.Now()),+ },+ )+ if err != nil {+ return err+ }+ _, err = ex.Exec(query, args...)+ return err+}++func (r *deviceAuthorizationRepository) FindByDeviceCode(ex lit.Executor, deviceCode string) (*models.DeviceAuthorization, error) {+ return r.findOne(ex, "device_code_hash = :v", shared.HashAuthToken(deviceCode))+}++func (r *deviceAuthorizationRepository) FindByUserCode(ex lit.Executor, userCode string) (*models.DeviceAuthorization, error) {+ // Codes are stored uppercase (generated from an uppercase alphabet); uppercase+ // the lookup so a lowercase-but-correct entry still matches.+ return r.findOne(ex, "user_code = :v", strings.ToUpper(userCode))+}++func (r *deviceAuthorizationRepository) findOne(ex lit.Executor, where, value string) (*models.DeviceAuthorization, error) {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ "SELECT device_code_hash, user_code, client_id, status, user_id, interval_seconds, last_polled_at, expires_at, created_at FROM device_authorizations WHERE "+where,+ lit.P{"v": value},+ )+ if err != nil {+ return nil, err+ }++ var (+ d models.DeviceAuthorization+ userId sql.NullInt64+ lastPolled sql.NullString+ expiresAt string+ createdAt string+ )+ err = ex.QueryRow(query, args...).Scan(&d.DeviceCodeHash, &d.UserCode, &d.ClientId, &d.Status, &userId, &d.IntervalSeconds, &lastPolled, &expiresAt, &createdAt)+ if errors.Is(err, sql.ErrNoRows) {+ return nil, nil+ }+ if err != nil {+ return nil, err+ }++ if userId.Valid {+ uid := int(userId.Int64)+ d.UserId = &uid+ }+ if d.LastPolledAt, err = shared.ParseNullableAuthTime(lastPolled); err != nil {+ return nil, err+ }+ if d.ExpiresAt, err = shared.ParseAuthTime(expiresAt); err != nil {+ return nil, err+ }+ if d.CreatedAt, err = shared.ParseAuthTime(createdAt); err != nil {+ return nil, err+ }+ return &d, nil+}++func (r *deviceAuthorizationRepository) Approve(ex lit.Executor, userCode string, userId int) (int64, error) {+ return r.updateStatus(ex, userCode, "approved", &userId)+}++func (r *deviceAuthorizationRepository) Deny(ex lit.Executor, userCode string) (int64, error) {+ return r.updateStatus(ex, userCode, "denied", nil)+}++func (r *deviceAuthorizationRepository) updateStatus(ex lit.Executor, userCode, status string, userId *int) (int64, error) {+ var uid any+ if userId != nil {+ uid = *userId+ }+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ "UPDATE device_authorizations SET status = :status, user_id = :user_id WHERE user_code = :user_code AND status = 'pending'",+ lit.P{"status": status, "user_id": uid, "user_code": strings.ToUpper(userCode)},+ )+ if err != nil {+ return 0, err+ }+ res, err := ex.Exec(query, args...)+ if err != nil {+ return 0, err+ }+ return res.RowsAffected()+}++func (r *deviceAuthorizationRepository) MarkPolled(ex lit.Executor, deviceCode string, polledAt time.Time, intervalSeconds int) error {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ "UPDATE device_authorizations SET last_polled_at = :polled, interval_seconds = :interval WHERE device_code_hash = :hash",+ lit.P{"polled": shared.FormatAuthTime(polledAt), "interval": intervalSeconds, "hash": shared.HashAuthToken(deviceCode)},+ )+ if err != nil {+ return err+ }+ _, err = ex.Exec(query, args...)+ return err+}++func (r *deviceAuthorizationRepository) Delete(ex lit.Executor, deviceCode string) (int64, error) {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ "DELETE FROM device_authorizations WHERE device_code_hash = :hash",+ lit.P{"hash": shared.HashAuthToken(deviceCode)},+ )+ if err != nil {+ return 0, err+ }+ res, err := ex.Exec(query, args...)+ if err != nil {+ return 0, err+ }+ return res.RowsAffected()+}++func (r *deviceAuthorizationRepository) PruneExpired(ex lit.Executor, now time.Time) (int64, error) {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ "DELETE FROM device_authorizations WHERE expires_at < :cutoff",+ lit.P{"cutoff": shared.FormatAuthTime(now)},+ )+ if err != nil {+ return 0, err+ }+ res, err := ex.Exec(query, args...)+ if err != nil {+ return 0, err+ }+ return res.RowsAffected()+}++var DeviceAuthorizationRepository = deviceAuthorizationRepository{}diff --git a/backend/app/repositories/transactional/sqlite/invitation.repository.go b/backend/app/repositories/transactional/sqlite/invitation.repository.gonew file mode 100644index 00000000..c48a93bc--- /dev/null+++ b/backend/app/repositories/transactional/sqlite/invitation.repository.go@@ -0,0 +1,100 @@+//go:build !transactional_pg++package sqlite++import (+ "database/sql"+ "time"++ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"++ "github.com/google/uuid"+ "github.com/tracewayapp/lit/v2"+)++type invitationRepository struct{}++func (r *invitationRepository) Create(tx *sql.Tx, organizationId int, email string, role string, invitedBy int, expiresAt time.Time) (*models.Invitation, error) {+ token := uuid.New().String()++ invitation := &models.Invitation{+ OrganizationId: organizationId,+ Email: email,+ Role: role,+ Token: token,+ InvitedBy: invitedBy,+ Status: "pending",+ ExpiresAt: expiresAt,+ CreatedAt: time.Now().UTC(),+ }++ id, err := lit.Insert(tx, invitation)+ if err != nil {+ return nil, err+ }+ invitation.Id = id++ return invitation, nil+}++func (r *invitationRepository) FindByToken(tx *sql.Tx, token string) (*models.Invitation, error) {+ return lit.SelectSingleNamed[models.Invitation](+ tx,+ `SELECT id, organization_id, email, role, token, invited_by, status, expires_at, accepted_at, created_at+ FROM invitations+ WHERE token = :token`,+ lit.P{"token": token},+ )+}++func (r *invitationRepository) FindByOrganization(tx *sql.Tx, organizationId int) ([]*models.InvitationWithInviter, error) {+ return lit.SelectNamed[models.InvitationWithInviter](+ tx,+ `SELECT i.id, i.organization_id, i.email, i.role, i.invited_by, u.name as inviter_name, i.status, i.expires_at, i.accepted_at, i.created_at+ FROM invitations i+ JOIN users u ON i.invited_by = u.id+ WHERE i.organization_id = :org_id AND i.status = 'pending'+ ORDER BY i.created_at DESC`,+ lit.P{"org_id": organizationId},+ )+}++func (r *invitationRepository) Update(tx *sql.Tx, invitation *models.Invitation) error {+ return lit.UpdateNamed[models.Invitation](+ tx,+ invitation,+ "id = :id",+ lit.P{"id": invitation.Id},+ )+}++func (r *invitationRepository) Delete(tx *sql.Tx, id int) error {+ return lit.DeleteNamed(db.Driver, tx, "DELETE FROM invitations WHERE id = :id", lit.P{"id": id})+}++func (r *invitationRepository) HasPendingInvitation(tx *sql.Tx, email string, organizationId int) (bool, error) {+ invitation, err := lit.SelectSingleNamed[models.Invitation](+ tx,+ `SELECT id, organization_id, email, role, token, invited_by, status, expires_at, accepted_at, created_at+ FROM invitations+ WHERE email = :email AND organization_id = :org_id AND status = 'pending'`,+ lit.P{"email": email, "org_id": organizationId},+ )+ if err != nil {+ return false, err+ }+ return invitation != nil, nil+}++func (r *invitationRepository) FindById(tx *sql.Tx, id int) (*models.Invitation, error) {+ return lit.SelectSingleNamed[models.Invitation](+ tx,+ `SELECT id, organization_id, email, role, token, invited_by, status, expires_at, accepted_at, created_at+ FROM invitations+ WHERE id = :id`,+ lit.P{"id": id},+ )+}++var InvitationRepository = invitationRepository{}diff --git a/backend/app/repositories/transactional/sqlite/metric_registry.repository.go b/backend/app/repositories/transactional/sqlite/metric_registry.repository.gonew file mode 100644index 00000000..6d10de5b--- /dev/null+++ b/backend/app/repositories/transactional/sqlite/metric_registry.repository.go@@ -0,0 +1,158 @@+//go:build !transactional_pg++package sqlite++import (+ "database/sql"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional/shared"+ "sync"+ "time"++ "github.com/tracewayapp/traceway/backend/app/models"++ "github.com/google/uuid"+ "github.com/tracewayapp/lit/v2"+)++type metricRegistryRepository struct {+ knownMetrics sync.Map+}++func (r *metricRegistryRepository) EnsureRegistered(tx *sql.Tx, projectId uuid.UUID, names []string) error {+ for _, name := range names {+ key := projectId.String() + ":" + name+ if _, loaded := r.knownMetrics.Load(key); loaded {+ continue+ }++ existing, err := r.FindByProjectAndName(tx, projectId, name)+ if err != nil {+ return err+ }+ if existing != nil {+ r.knownMetrics.Store(key, true)+ continue+ }++ metricType := defaultMetricType(name)+ unit := defaultUnit(name)++ entry := &models.MetricRegistry{+ ProjectId: projectId,+ Name: name,+ MetricType: metricType,+ Unit: unit,+ Description: "",+ CreatedAt: time.Now().UTC(),+ }++ _, err = lit.Insert[models.MetricRegistry](tx, entry)+ if err != nil {+ return err+ }+ r.knownMetrics.Store(key, true)+ }+ return nil+}++func (r *metricRegistryRepository) FindByProject(tx *sql.Tx, projectId uuid.UUID) ([]*models.MetricRegistry, error) {+ return lit.SelectNamed[models.MetricRegistry](+ tx,+ "SELECT id, project_id, name, metric_type, unit, description, created_at FROM metric_registry WHERE project_id = :project_id ORDER BY name ASC",+ lit.P{"project_id": projectId},+ )+}++func (r *metricRegistryRepository) FindByProjectAndName(tx *sql.Tx, projectId uuid.UUID, name string) (*models.MetricRegistry, error) {+ return lit.SelectSingleNamed[models.MetricRegistry](+ tx,+ "SELECT id, project_id, name, metric_type, unit, description, created_at FROM metric_registry WHERE project_id = :project_id AND name = :name",+ lit.P{"project_id": projectId, "name": name},+ )+}++func (r *metricRegistryRepository) Update(tx *sql.Tx, entry *models.MetricRegistry) error {+ return lit.UpdateNamed(tx, entry, "id = :id", lit.P{"id": entry.Id})+}++func (r *metricRegistryRepository) EnsureRegisteredWithUnits(tx *sql.Tx, projectId uuid.UUID, entries []shared.MetricRegistrationEntry) error {+ for _, entry := range entries {+ key := projectId.String() + ":" + entry.Name+ if _, loaded := r.knownMetrics.Load(key); loaded {+ continue+ }++ existing, err := r.FindByProjectAndName(tx, projectId, entry.Name)+ if err != nil {+ return err+ }+ if existing != nil {+ r.knownMetrics.Store(key, true)+ continue+ }++ metricType := entry.MetricType+ if metricType == "" {+ metricType = defaultMetricType(entry.Name)+ }+ unit := entry.Unit+ if unit == "" {+ unit = defaultUnit(entry.Name)+ }++ rec := &models.MetricRegistry{+ ProjectId: projectId,+ Name: entry.Name,+ MetricType: metricType,+ Unit: unit,+ Description: "",+ CreatedAt: time.Now().UTC(),+ }++ _, err = lit.Insert[models.MetricRegistry](tx, rec)+ if err != nil {+ return err+ }+ r.knownMetrics.Store(key, true)+ }+ return nil+}++func defaultMetricType(name string) string {+ switch name {+ case models.MetricNameNumGC:+ return "counter"+ case models.MetricNameGCPauseTotal:+ return "counter"+ default:+ return "gauge"+ }+}++func defaultUnit(name string) string {+ switch name {+ case models.MetricNameCpuUsage:+ return "%"+ case models.MetricNameMemoryUsage, models.MetricNameMemoryTotal:+ return "MB"+ case models.MetricNameGoRoutines, models.MetricNameHeapObjects:+ return "count"+ case models.MetricNameNumGC:+ return "count"+ case models.MetricNameGCPauseTotal:+ return "ns"+ default:+ return ""+ }+}++func (r *metricRegistryRepository) KnownCount() int {+ count := 0+ r.knownMetrics.Range(func(_, _ any) bool {+ count+++ return true+ })+ return count+}++var MetricRegistryRepository = &metricRegistryRepository{}diff --git a/backend/app/repositories/transactional/sqlite/notification_channel.repository.go b/backend/app/repositories/transactional/sqlite/notification_channel.repository.gonew file mode 100644index 00000000..50e2ee99--- /dev/null+++ b/backend/app/repositories/transactional/sqlite/notification_channel.repository.go@@ -0,0 +1,53 @@+//go:build !transactional_pg++package sqlite++import (+ "database/sql"++ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"++ "github.com/google/uuid"+ "github.com/tracewayapp/lit/v2"+)++type notificationChannelRepository struct{}++func (r *notificationChannelRepository) FindByProject(tx *sql.Tx, projectId uuid.UUID) ([]*models.NotificationChannel, error) {+ return lit.SelectNamed[models.NotificationChannel](+ tx,+ "SELECT id, project_id, name, channel_type, config, enabled, created_by, created_at, updated_at FROM notification_channels WHERE project_id = :project_id ORDER BY created_at DESC",+ lit.P{"project_id": projectId},+ )+}++func (r *notificationChannelRepository) FindById(tx *sql.Tx, id int) (*models.NotificationChannel, error) {+ return lit.SelectSingleNamed[models.NotificationChannel](+ tx,+ "SELECT id, project_id, name, channel_type, config, enabled, created_by, created_at, updated_at FROM notification_channels WHERE id = :id",+ lit.P{"id": id},+ )+}++func (r *notificationChannelRepository) Create(tx *sql.Tx, channel *models.NotificationChannel) (int, error) {+ return lit.Insert[models.NotificationChannel](tx, channel)+}++func (r *notificationChannelRepository) Update(tx *sql.Tx, channel *models.NotificationChannel) error {+ return lit.UpdateNamed(tx, channel, "id = :id", lit.P{"id": channel.Id})+}++func (r *notificationChannelRepository) Delete(tx *sql.Tx, id int) error {+ return lit.DeleteNamed(db.Driver, tx, "DELETE FROM notification_channels WHERE id = :id", lit.P{"id": id})+}++func (r *notificationChannelRepository) FindEnabledByProject(tx *sql.Tx, projectId uuid.UUID) ([]*models.NotificationChannel, error) {+ return lit.SelectNamed[models.NotificationChannel](+ tx,+ "SELECT id, project_id, name, channel_type, config, enabled, created_by, created_at, updated_at FROM notification_channels WHERE project_id = :project_id AND enabled = true",+ lit.P{"project_id": projectId},+ )+}++var NotificationChannelRepository = notificationChannelRepository{}diff --git a/backend/app/repositories/transactional/sqlite/notification_rule.repository.go b/backend/app/repositories/transactional/sqlite/notification_rule.repository.gonew file mode 100644index 00000000..8722a201--- /dev/null+++ b/backend/app/repositories/transactional/sqlite/notification_rule.repository.go@@ -0,0 +1,92 @@+//go:build !transactional_pg++package sqlite++import (+ "database/sql"+ "time"++ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"++ "github.com/google/uuid"+ "github.com/tracewayapp/lit/v2"+)++type notificationRuleRepository struct{}++func (r *notificationRuleRepository) FindByProjectWithChannel(tx *sql.Tx, projectId uuid.UUID) ([]*models.NotificationRuleWithChannel, error) {+ return lit.SelectNamed[models.NotificationRuleWithChannel](+ tx,+ `SELECT r.id, r.project_id, r.channel_id, r.name, r.rule_type, r.config, r.enabled, r.cooldown_minutes, r.severity, r.snoozed_until, r.created_by, r.created_at, r.updated_at,+ c.name as channel_name, c.channel_type as channel_type+ FROM notification_rules r+ JOIN notification_channels c ON c.id = r.channel_id+ WHERE r.project_id = :project_id+ ORDER BY r.created_at DESC`,+ lit.P{"project_id": projectId},+ )+}++func (r *notificationRuleRepository) FindById(tx *sql.Tx, id int) (*models.NotificationRule, error) {+ return lit.SelectSingleNamed[models.NotificationRule](+ tx,+ "SELECT id, project_id, channel_id, name, rule_type, config, enabled, cooldown_minutes, severity, snoozed_until, created_by, created_at, updated_at FROM notification_rules WHERE id = :id",+ lit.P{"id": id},+ )+}++func (r *notificationRuleRepository) FindEnabledPolledRules(tx *sql.Tx) ([]*models.NotificationRuleWithChannel, error) {+ return lit.Select[models.NotificationRuleWithChannel](+ tx,+ `SELECT r.id, r.project_id, r.channel_id, r.name, r.rule_type, r.config, r.enabled, r.cooldown_minutes, r.severity, r.snoozed_until, r.created_by, r.created_at, r.updated_at,+ c.name as channel_name, c.channel_type as channel_type+ FROM notification_rules r+ JOIN notification_channels c ON c.id = r.channel_id+ WHERE r.enabled = true AND c.enabled = true+ AND r.rule_type NOT IN ('new_error', 'error_regression', 'ai_trace_cost')`,+ )+}++func (r *notificationRuleRepository) FindEnabledEventRules(tx *sql.Tx, projectId uuid.UUID) ([]*models.NotificationRuleWithChannel, error) {+ return lit.SelectNamed[models.NotificationRuleWithChannel](+ tx,+ `SELECT r.id, r.project_id, r.channel_id, r.name, r.rule_type, r.config, r.enabled, r.cooldown_minutes, r.severity, r.snoozed_until, r.created_by, r.created_at, r.updated_at,+ c.name as channel_name, c.channel_type as channel_type+ FROM notification_rules r+ JOIN notification_channels c ON c.id = r.channel_id+ WHERE r.project_id = :project_id AND r.enabled = true AND c.enabled = true+ AND r.rule_type IN ('new_error', 'error_regression', 'ai_trace_cost')`,+ lit.P{"project_id": projectId},+ )+}++func (r *notificationRuleRepository) Create(tx *sql.Tx, rule *models.NotificationRule) (int, error) {+ return lit.Insert[models.NotificationRule](tx, rule)+}++func (r *notificationRuleRepository) Update(tx *sql.Tx, rule *models.NotificationRule) error {+ return lit.UpdateNamed(tx, rule, "id = :id", lit.P{"id": rule.Id})+}++func (r *notificationRuleRepository) Delete(tx *sql.Tx, id int) error {+ return lit.DeleteNamed(db.Driver, tx, "DELETE FROM notification_rules WHERE id = :id", lit.P{"id": id})+}++func (r *notificationRuleRepository) UpdateEnabled(tx *sql.Tx, id int, enabled bool) error {+ q, a, err := lit.ParseNamedQuery(db.Driver, "UPDATE notification_rules SET enabled = :enabled, updated_at = :updated_at WHERE id = :id", lit.P{"enabled": enabled, "updated_at": time.Now().UTC(), "id": id})+ if err != nil {+ return err+ }+ return lit.UpdateNative(tx, q, a...)+}++func (r *notificationRuleRepository) UpdateSnoozedUntil(tx *sql.Tx, id int, snoozedUntil *time.Time) error {+ q, a, err := lit.ParseNamedQuery(db.Driver, "UPDATE notification_rules SET snoozed_until = :snoozed_until, updated_at = :updated_at WHERE id = :id", lit.P{"snoozed_until": snoozedUntil, "updated_at": time.Now().UTC(), "id": id})+ if err != nil {+ return err+ }+ return lit.UpdateNative(tx, q, a...)+}++var NotificationRuleRepository = notificationRuleRepository{}diff --git a/backend/app/repositories/transactional/sqlite/oauth_client.repository.go b/backend/app/repositories/transactional/sqlite/oauth_client.repository.gonew file mode 100644index 00000000..dac6d341--- /dev/null+++ b/backend/app/repositories/transactional/sqlite/oauth_client.repository.go@@ -0,0 +1,94 @@+//go:build !transactional_pg++package sqlite++import (+ "database/sql"+ "encoding/json"+ "errors"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional/shared"+ "time"++ "github.com/tracewayapp/lit/v2"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"+)++type oauthClientRepository struct{}++func (r *oauthClientRepository) Create(ex lit.Executor, client *models.OauthClient) error {+ uris, err := json.Marshal(client.RedirectUris)+ if err != nil {+ return err+ }+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ `INSERT INTO oauth_clients (id, name, redirect_uris, created_at)+ VALUES (:id, :name, :redirect_uris, :created_at)`,+ lit.P{+ "id": client.Id,+ "name": client.Name,+ "redirect_uris": string(uris),+ "created_at": shared.FormatAuthTime(client.CreatedAt),+ },+ )+ if err != nil {+ return err+ }+ _, err = ex.Exec(query, args...)+ return err+}++func (r *oauthClientRepository) FindById(ex lit.Executor, id string) (*models.OauthClient, error) {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ "SELECT id, name, redirect_uris, created_at FROM oauth_clients WHERE id = :id",+ lit.P{"id": id},+ )+ if err != nil {+ return nil, err+ }++ var (+ c models.OauthClient+ uris string+ createdAt string+ )+ err = ex.QueryRow(query, args...).Scan(&c.Id, &c.Name, &uris, &createdAt)+ if errors.Is(err, sql.ErrNoRows) {+ return nil, nil+ }+ if err != nil {+ return nil, err+ }++ if err := json.Unmarshal([]byte(uris), &c.RedirectUris); err != nil {+ return nil, err+ }+ if c.CreatedAt, err = shared.ParseAuthTime(createdAt); err != nil {+ return nil, err+ }+ return &c, nil+}++const staleOauthClientRetention = 30 * 24 * time.Hour++func (r *oauthClientRepository) PruneStale(ex lit.Executor, now time.Time) (int64, error) {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ `DELETE FROM oauth_clients WHERE created_at < :cutoff+ AND NOT EXISTS (SELECT 1 FROM refresh_tokens WHERE refresh_tokens.client_id = oauth_clients.id)+ AND NOT EXISTS (SELECT 1 FROM authorization_codes WHERE authorization_codes.client_id = oauth_clients.id)`,+ lit.P{"cutoff": shared.FormatAuthTime(now.Add(-staleOauthClientRetention))},+ )+ if err != nil {+ return 0, err+ }+ res, err := ex.Exec(query, args...)+ if err != nil {+ return 0, err+ }+ return res.RowsAffected()+}++var OauthClientRepository = oauthClientRepository{}diff --git a/backend/app/repositories/transactional/sqlite/oauth_session.repository.go b/backend/app/repositories/transactional/sqlite/oauth_session.repository.gonew file mode 100644index 00000000..f602f7af--- /dev/null+++ b/backend/app/repositories/transactional/sqlite/oauth_session.repository.go@@ -0,0 +1,94 @@+//go:build !transactional_pg++package sqlite++import (+ "database/sql"+ "errors"+ "time"++ "github.com/tracewayapp/lit/v2"+ "github.com/tracewayapp/traceway/backend/app/db"+)++type oauthSessionRepository struct{}++func (r *oauthSessionRepository) Get(tx *sql.Tx, id string) ([]byte, error) {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ "SELECT data FROM oauth_sessions WHERE id = :id AND expires_at > :now",+ lit.P{"id": id, "now": time.Now().UTC().Format(time.RFC3339Nano)},+ )+ if err != nil {+ return nil, err+ }++ var data []byte+ if err := tx.QueryRow(query, args...).Scan(&data); err != nil {+ if errors.Is(err, sql.ErrNoRows) {+ return nil, nil+ }+ return nil, err+ }+ return data, nil+}++func (r *oauthSessionRepository) Save(tx *sql.Tx, id string, data []byte, expiresAt time.Time) error {+ deleteQuery, deleteArgs, err := lit.ParseNamedQuery(+ db.Driver,+ "DELETE FROM oauth_sessions WHERE id = :id",+ lit.P{"id": id},+ )+ if err != nil {+ return err+ }+ if _, err := tx.Exec(deleteQuery, deleteArgs...); err != nil {+ return err+ }++ insertQuery, insertArgs, err := lit.ParseNamedQuery(+ db.Driver,+ "INSERT INTO oauth_sessions (id, data, expires_at) VALUES (:id, :data, :expires_at)",+ lit.P{+ "id": id,+ "data": data,+ "expires_at": expiresAt.UTC().Format(time.RFC3339Nano),+ },+ )+ if err != nil {+ return err+ }+ _, err = tx.Exec(insertQuery, insertArgs...)+ return err+}++func (r *oauthSessionRepository) Delete(tx *sql.Tx, id string) error {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ "DELETE FROM oauth_sessions WHERE id = :id",+ lit.P{"id": id},+ )+ if err != nil {+ return err+ }+ _, err = tx.Exec(query, args...)+ return err+}++func (r *oauthSessionRepository) PruneExpired(tx *sql.Tx, now time.Time) (int64, error) {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ "DELETE FROM oauth_sessions WHERE expires_at < :cutoff",+ lit.P{"cutoff": now.UTC().Format(time.RFC3339Nano)},+ )+ if err != nil {+ return 0, err+ }+ result, err := tx.Exec(query, args...)+ if err != nil {+ return 0, err+ }+ return result.RowsAffected()+}++var OAuthSessionRepository = oauthSessionRepository{}diff --git a/backend/app/repositories/transactional/sqlite/organization.repository.go b/backend/app/repositories/transactional/sqlite/organization.repository.gonew file mode 100644index 00000000..a8527f42--- /dev/null+++ b/backend/app/repositories/transactional/sqlite/organization.repository.go@@ -0,0 +1,209 @@+//go:build !transactional_pg++package sqlite++import (+ "database/sql"+ "time"++ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"++ "github.com/tracewayapp/lit/v2"+)++type organizationRepository struct{}++func (r *organizationRepository) Create(tx *sql.Tx, name string, timezone string) (*models.Organization, error) {+ org := &models.Organization{+ Name: name,+ Timezone: timezone,+ CreatedAt: time.Now().UTC(),+ }++ id, err := lit.Insert(tx, org)+ if err != nil {+ return nil, err+ }+ org.Id = id++ return org, nil+}++func (r *organizationRepository) HasOrganizations(tx *sql.Tx) (bool, error) {+ result, err := lit.SelectSingle[models.CountResult](+ tx,+ `SELECT COUNT(*) as count+ FROM organizations`,+ )+ if err != nil {+ return false, err+ }+ if result == nil {+ return false, nil+ }++ return result.Count > 0, nil+}++func (r *organizationRepository) FindFirst(tx *sql.Tx) (*models.Organization, error) {+ return lit.SelectSingle[models.Organization](+ tx,+ "SELECT id, name, timezone, created_at FROM organizations ORDER BY created_at ASC LIMIT 1",+ )+}++func (r *organizationRepository) FindByName(tx *sql.Tx, name string) (*models.Organization, error) {+ return lit.SelectSingleNamed[models.Organization](+ tx,+ "SELECT id, name, timezone, created_at FROM organizations WHERE name = :name LIMIT 1",+ lit.P{"name": name},+ )+}++func (r *organizationRepository) FindById(tx *sql.Tx, id int) (*models.Organization, error) {+ return lit.SelectSingleNamed[models.Organization](+ tx,+ "SELECT id, name, timezone, created_at FROM organizations WHERE id = :id",+ lit.P{"id": id},+ )+}++func (r *organizationRepository) FindByUserId(tx *sql.Tx, userId int) ([]*models.Organization, error) {+ return lit.SelectNamed[models.Organization](+ tx,+ `SELECT o.id, o.name, o.created_at+ FROM organizations o+ INNER JOIN organization_users ou ON o.id = ou.organization_id+ WHERE ou.user_id = :user_id+ ORDER BY o.created_at ASC`,+ lit.P{"user_id": userId},+ )+}++func (r *organizationRepository) AddUser(tx *sql.Tx, organizationId int, userId int, role string) (*models.OrganizationUser, error) {+ orgUser := &models.OrganizationUser{+ UserId: userId,+ OrganizationId: organizationId,+ Role: role,+ CreatedAt: time.Now().UTC(),+ }++ id, err := lit.Insert(tx, orgUser)+ if err != nil {+ return nil, err+ }+ orgUser.Id = id++ return orgUser, nil+}++func (r *organizationRepository) GetUserRole(tx *sql.Tx, organizationId int, userId int) (string, error) {+ orgUser, err := lit.SelectSingleNamed[models.OrganizationUser](+ tx,+ "SELECT id, user_id, organization_id, role, created_at FROM organization_users WHERE organization_id = :org_id AND user_id = :user_id",+ lit.P{"org_id": organizationId, "user_id": userId},+ )+ if err != nil {+ return "", err+ }+ if orgUser == nil {+ return "", nil // User not in organization+ }+ return orgUser.Role, nil+}++func (r *organizationRepository) CountMembers(tx *sql.Tx, organizationId int) (int, error) {+ result, err := lit.SelectSingleNamed[models.CountResult](+ tx,+ `SELECT COUNT(*) as count FROM organization_users WHERE organization_id = :org_id`,+ lit.P{"org_id": organizationId},+ )+ if err != nil {+ return 0, err+ }+ if result == nil {+ return 0, nil+ }+ return result.Count, nil+}++func (r *organizationRepository) GetMembersWithDetails(tx *sql.Tx, organizationId int) ([]*models.OrganizationMember, error) {+ return lit.SelectNamed[models.OrganizationMember](+ tx,+ `SELECT u.id, u.email, u.name, ou.role, ou.created_at+ FROM users u+ JOIN organization_users ou ON u.id = ou.user_id+ WHERE ou.organization_id = :org_id+ ORDER BY ou.created_at ASC`,+ lit.P{"org_id": organizationId},+ )+}++func (r *organizationRepository) IsOwner(tx *sql.Tx, organizationId int, userId int) (bool, error) {+ role, err := r.GetUserRole(tx, organizationId, userId)+ if err != nil {+ return false, err+ }+ return role == "owner", nil+}++func (r *organizationRepository) UpdateUserRole(tx *sql.Tx, organizationId int, userId int, role string) error {+ q, a, err := lit.ParseNamedQuery(db.Driver, "UPDATE organization_users SET role = :role WHERE organization_id = :org_id AND user_id = :user_id", lit.P{"role": role, "org_id": organizationId, "user_id": userId})+ if err != nil {+ return err+ }+ return lit.UpdateNative(tx, q, a...)+}++func (r *organizationRepository) RemoveUser(tx *sql.Tx, organizationId int, userId int) error {+ return lit.DeleteNamed(db.Driver, tx, "DELETE FROM organization_users WHERE organization_id = :org_id AND user_id = :user_id", lit.P{"org_id": organizationId, "user_id": userId})+}++func (r *organizationRepository) IsUserMember(tx *sql.Tx, organizationId int, userId int) (bool, error) {+ role, err := r.GetUserRole(tx, organizationId, userId)+ if err != nil {+ return false, err+ }+ return role != "", nil+}++func (r *organizationRepository) IsUserMemberByEmail(tx *sql.Tx, organizationId int, email string) (bool, error) {+ result, err := lit.SelectSingleNamed[models.CountResult](+ tx,+ `SELECT COUNT(*) as count+ FROM organization_users ou+ JOIN users u ON u.id = ou.user_id+ WHERE ou.organization_id = :org_id AND u.email = :email`,+ lit.P{"org_id": organizationId, "email": email},+ )+ if err != nil {+ return false, err+ }+ if result == nil {+ return false, nil+ }+ return result.Count > 0, nil+}++func (r *organizationRepository) FindByUserIdWithRoles(tx *sql.Tx, userId int) ([]*models.UserOrganizationResponse, error) {+ return lit.SelectNamed[models.UserOrganizationResponse](+ tx,+ `SELECT o.id, o.name, ou.role, o.timezone+ FROM organizations o+ INNER JOIN organization_users ou ON o.id = ou.organization_id+ WHERE ou.user_id = :user_id+ ORDER BY o.created_at ASC`,+ lit.P{"user_id": userId},+ )+}++func (r *organizationRepository) UpdateTimezone(tx *sql.Tx, organizationId int, timezone string) error {+ q, a, err := lit.ParseNamedQuery(db.Driver, "UPDATE organizations SET timezone = :timezone WHERE id = :id", lit.P{"timezone": timezone, "id": organizationId})+ if err != nil {+ return err+ }+ return lit.UpdateNative(tx, q, a...)+}++var OrganizationRepository = organizationRepository{}diff --git a/backend/app/repositories/transactional/sqlite/personal_access_token.repository.go b/backend/app/repositories/transactional/sqlite/personal_access_token.repository.gonew file mode 100644index 00000000..d839deac--- /dev/null+++ b/backend/app/repositories/transactional/sqlite/personal_access_token.repository.go@@ -0,0 +1,181 @@+//go:build !transactional_pg++package sqlite++import (+ "database/sql"+ "errors"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional/shared"+ "time"++ "github.com/tracewayapp/lit/v2"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"+)++type personalAccessTokenRepository struct{}++func (r *personalAccessTokenRepository) Create(ex lit.Executor, id, token, prefix string, userId int, name string, expiresAt *time.Time) error {+ var expires any+ if expiresAt != nil {+ expires = shared.FormatAuthTime(*expiresAt)+ }+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ `INSERT INTO personal_access_tokens (id, token_hash, prefix, user_id, name, revoked, expires_at, created_at)+ VALUES (:id, :hash, :prefix, :user_id, :name, :revoked, :expires_at, :created_at)`,+ lit.P{+ "id": id,+ "hash": shared.HashAuthToken(token),+ "prefix": prefix,+ "user_id": userId,+ "name": name,+ "revoked": false,+ "expires_at": expires,+ "created_at": shared.FormatAuthTime(time.Now()),+ },+ )+ if err != nil {+ return err+ }+ _, err = ex.Exec(query, args...)+ return err+}++func (r *personalAccessTokenRepository) FindActiveByToken(ex lit.Executor, token string) (*shared.ActivePAT, error) {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ `SELECT p.id, p.user_id, p.revoked, p.expires_at, p.last_used_at, u.email+ FROM personal_access_tokens p+ JOIN users u ON u.id = p.user_id+ WHERE p.token_hash = :hash`,+ lit.P{"hash": shared.HashAuthToken(token)},+ )+ if err != nil {+ return nil, err+ }++ var (+ pat shared.ActivePAT+ revoked bool+ expiresAt sql.NullString+ lastUsed sql.NullString+ )+ err = ex.QueryRow(query, args...).Scan(&pat.Id, &pat.UserId, &revoked, &expiresAt, &lastUsed, &pat.Email)+ if errors.Is(err, sql.ErrNoRows) {+ return nil, nil+ }+ if err != nil {+ return nil, err+ }++ if revoked {+ return nil, nil+ }+ expiry, err := shared.ParseNullableAuthTime(expiresAt)+ if err != nil {+ return nil, err+ }+ if expiry != nil && time.Now().After(*expiry) {+ return nil, nil+ }+ if pat.LastUsedAt, err = shared.ParseNullableAuthTime(lastUsed); err != nil {+ return nil, err+ }+ return &pat, nil+}++func (r *personalAccessTokenRepository) ListByUser(ex lit.Executor, userId int) ([]*models.PersonalAccessToken, error) {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ `SELECT id, prefix, name, last_used_at, expires_at, created_at+ FROM personal_access_tokens+ WHERE user_id = :user_id AND revoked = :revoked+ ORDER BY created_at DESC`,+ lit.P{"user_id": userId, "revoked": false},+ )+ if err != nil {+ return nil, err+ }++ rows, err := ex.Query(query, args...)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ tokens := []*models.PersonalAccessToken{}+ for rows.Next() {+ var (+ pat models.PersonalAccessToken+ lastUsed sql.NullString+ expiresAt sql.NullString+ createdAt string+ )+ if err := rows.Scan(&pat.Id, &pat.Prefix, &pat.Name, &lastUsed, &expiresAt, &createdAt); err != nil {+ return nil, err+ }+ if pat.LastUsedAt, err = shared.ParseNullableAuthTime(lastUsed); err != nil {+ return nil, err+ }+ if pat.ExpiresAt, err = shared.ParseNullableAuthTime(expiresAt); err != nil {+ return nil, err+ }+ if pat.CreatedAt, err = shared.ParseAuthTime(createdAt); err != nil {+ return nil, err+ }+ tokens = append(tokens, &pat)+ }+ return tokens, rows.Err()+}++func (r *personalAccessTokenRepository) Revoke(ex lit.Executor, id string, userId int) (int64, error) {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ "UPDATE personal_access_tokens SET revoked = :revoked WHERE id = :id AND user_id = :user_id AND revoked = :active",+ lit.P{"revoked": true, "id": id, "user_id": userId, "active": false},+ )+ if err != nil {+ return 0, err+ }+ res, err := ex.Exec(query, args...)+ if err != nil {+ return 0, err+ }+ return res.RowsAffected()+}++// PruneExpired deletes rows that are no longer usable: revoked tokens, and+// tokens past their (optional) expiry. Unlike device codes and refresh tokens,+// PAT expiry was previously only enforced lazily at read time, so expired and+// revoked rows accumulated indefinitely.+func (r *personalAccessTokenRepository) PruneExpired(ex lit.Executor, now time.Time) (int64, error) {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ "DELETE FROM personal_access_tokens WHERE revoked = :revoked OR (expires_at IS NOT NULL AND expires_at < :cutoff)",+ lit.P{"revoked": true, "cutoff": shared.FormatAuthTime(now)},+ )+ if err != nil {+ return 0, err+ }+ res, err := ex.Exec(query, args...)+ if err != nil {+ return 0, err+ }+ return res.RowsAffected()+}++func (r *personalAccessTokenRepository) TouchLastUsed(ex lit.Executor, id string, usedAt time.Time) error {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ "UPDATE personal_access_tokens SET last_used_at = :used WHERE id = :id",+ lit.P{"used": shared.FormatAuthTime(usedAt), "id": id},+ )+ if err != nil {+ return err+ }+ _, err = ex.Exec(query, args...)+ return err+}++var PersonalAccessTokenRepository = personalAccessTokenRepository{}diff --git a/backend/app/repositories/transactional/sqlite/project.repository.go b/backend/app/repositories/transactional/sqlite/project.repository.gonew file mode 100644index 00000000..35231644--- /dev/null+++ b/backend/app/repositories/transactional/sqlite/project.repository.go@@ -0,0 +1,268 @@+//go:build !transactional_pg++package sqlite++import (+ "database/sql"+ "fmt"+ "strings"+ "time"++ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"++ "github.com/google/uuid"+ "github.com/tracewayapp/lit/v2"+)++type projectRepository struct{}++type projectWithRole struct {+ Id uuid.UUID `lit:"id"`+ Name string `lit:"name"`+ Token string `lit:"token"`+ Framework string `lit:"framework"`+ OrganizationId *int `lit:"organization_id"`+ CreatedAt time.Time `lit:"created_at"`+ SourceMapToken *string `lit:"source_map_token"`+ DropHealthyHealthchecks bool `lit:"drop_healthy_healthchecks"`+ HealthcheckPaths models.StringSlice `lit:"healthcheck_paths"`+ ProfileLabelAllowlist models.StringSlice `lit:"profile_label_allowlist"`+ Role string `lit:"role"`+}++func init() {+ models.ExtensionModelRegistrations = append(models.ExtensionModelRegistrations, func(driver lit.Driver) {+ lit.RegisterModel[projectWithRole](driver)+ })+}++func (p *projectRepository) FindAllWithBackendUrlByUserId(tx *sql.Tx, userId int) ([]*models.ProjectWithBackendUrl, error) {+ rows, err := lit.SelectNamed[projectWithRole](+ tx,+ `SELECT DISTINCT p.id, p.name, p.token, p.framework, p.organization_id, p.created_at, p.source_map_token, p.drop_healthy_healthchecks, p.healthcheck_paths, p.profile_label_allowlist, ou.role+ FROM projects p+ INNER JOIN organization_users ou ON p.organization_id = ou.organization_id+ WHERE ou.user_id = :user_id+ ORDER BY p.created_at ASC`,+ lit.P{"user_id": userId},+ )+ if err != nil {+ return nil, err+ }++ result := make([]*models.ProjectWithBackendUrl, 0, len(rows))+ for _, row := range rows {+ token := row.Token+ sourceMapToken := row.SourceMapToken+ if row.Role == "readonly" {+ token = "read-only-hidden-token"+ sourceMapToken = nil+ }++ project := models.Project{+ Id: row.Id,+ Name: row.Name,+ Token: token,+ Framework: row.Framework,+ OrganizationId: row.OrganizationId,+ CreatedAt: row.CreatedAt,+ SourceMapToken: sourceMapToken,+ DropHealthyHealthchecks: row.DropHealthyHealthchecks,+ HealthcheckPaths: row.HealthcheckPaths,+ ProfileLabelAllowlist: row.ProfileLabelAllowlist,+ }+ result = append(result, project.ToProjectWithBackendUrl())+ }++ return result, nil+}++func (p *projectRepository) FindAll(tx *sql.Tx) ([]*models.Project, error) {+ return lit.Select[models.Project](+ tx,+ "SELECT id, name, token, framework, organization_id, created_at, source_map_token, drop_healthy_healthchecks, healthcheck_paths, profile_label_allowlist FROM projects ORDER BY created_at ASC",+ )+}++func (p *projectRepository) FindByToken(tx *sql.Tx, token string) (*models.Project, error) {+ return lit.SelectSingleNamed[models.Project](+ tx,+ "SELECT id, name, token, framework, organization_id, created_at, source_map_token, drop_healthy_healthchecks, healthcheck_paths, profile_label_allowlist FROM projects WHERE token = :token",+ lit.P{"token": token},+ )+}++func (p *projectRepository) FindById(tx *sql.Tx, id uuid.UUID) (*models.Project, error) {+ return lit.SelectSingleNamed[models.Project](+ tx,+ "SELECT id, name, token, framework, organization_id, created_at, source_map_token, drop_healthy_healthchecks, healthcheck_paths, profile_label_allowlist FROM projects WHERE id = :id",+ lit.P{"id": id},+ )+}++func (p *projectRepository) Create(tx *sql.Tx, name string, framework string) (*models.Project, error) {+ project := &models.Project{+ Id: uuid.New(),+ Name: name,+ Token: generateSecureToken(),+ Framework: framework,+ CreatedAt: time.Now().UTC(),+ DropHealthyHealthchecks: true,+ }++ err := lit.InsertExistingUuid(tx, project)+ if err != nil {+ return nil, err+ }++ return project, nil+}++func (p *projectRepository) CreateWithOrganization(tx *sql.Tx, name string, framework string, organizationId int) (*models.Project, error) {+ project := &models.Project{+ Id: uuid.New(),+ Name: name,+ Token: generateSecureToken(),+ Framework: framework,+ OrganizationId: &organizationId,+ CreatedAt: time.Now().UTC(),+ DropHealthyHealthchecks: true,+ ProfileLabelAllowlist: models.StringSlice{},+ }++ if frameworkRequiresSymbolUpload(framework) {+ token := generateSecureToken()+ project.SourceMapToken = &token+ }++ err := lit.InsertExistingUuid(tx, project)+ if err != nil {+ return nil, err+ }++ return project, nil+}++func (p *projectRepository) FindByOrganizationId(tx *sql.Tx, organizationId int) ([]*models.Project, error) {+ return lit.SelectNamed[models.Project](+ tx,+ "SELECT id, name, token, framework, organization_id, created_at, source_map_token, drop_healthy_healthchecks, healthcheck_paths, profile_label_allowlist FROM projects WHERE organization_id = :org_id ORDER BY created_at ASC",+ lit.P{"org_id": organizationId},+ )+}++func (p *projectRepository) FindByUserId(tx *sql.Tx, userId int) ([]*models.Project, error) {+ return lit.SelectNamed[models.Project](+ tx,+ `SELECT DISTINCT p.id, p.name, p.token, p.framework, p.organization_id, p.created_at, p.source_map_token, p.drop_healthy_healthchecks, p.healthcheck_paths, p.profile_label_allowlist+ FROM projects p+ INNER JOIN organization_users ou ON p.organization_id = ou.organization_id+ WHERE ou.user_id = :user_id+ ORDER BY p.created_at ASC`,+ lit.P{"user_id": userId},+ )+}++func (p *projectRepository) UserHasAccess(tx *sql.Tx, projectId uuid.UUID, userId int) (bool, error) {+ result, err := lit.SelectSingleNamed[models.CountResult](+ tx,+ `SELECT COUNT(*) as count+ FROM projects p+ INNER JOIN organization_users ou ON p.organization_id = ou.organization_id+ WHERE p.id = :project_id AND ou.user_id = :user_id`,+ lit.P{"project_id": projectId, "user_id": userId},+ )+ if err != nil {+ return false, err+ }+ if result == nil {+ return false, nil+ }++ return result.Count > 0, nil+}++func (p *projectRepository) GenerateSourceMapToken(tx *sql.Tx, projectId uuid.UUID) (string, error) {+ project, err := p.FindById(tx, projectId)+ if err != nil {+ return "", err+ }+ if project == nil {+ return "", fmt.Errorf("project not found: %s", projectId)+ }++ token := generateSecureToken()+ project.SourceMapToken = &token+ err = lit.UpdateNamed[models.Project](tx, project, "id = :id", lit.P{"id": projectId})+ if err != nil {+ return "", err+ }+ return token, nil+}++func (p *projectRepository) Update(tx *sql.Tx, id uuid.UUID, name string, framework string, dropHealthyHealthchecks *bool, healthcheckPaths *[]string, profileLabelAllowlist *[]string) (*models.Project, error) {+ project, err := p.FindById(tx, id)+ if err != nil {+ return nil, err+ }+ if project == nil {+ return nil, fmt.Errorf("project not found: %s", id)+ }+ project.Name = name+ project.Framework = framework+ if dropHealthyHealthchecks != nil {+ project.DropHealthyHealthchecks = *dropHealthyHealthchecks+ }+ if healthcheckPaths != nil {+ project.HealthcheckPaths = models.StringSlice(*healthcheckPaths)+ }+ if profileLabelAllowlist != nil {+ project.ProfileLabelAllowlist = models.StringSlice(*profileLabelAllowlist)+ }+ err = lit.UpdateNamed[models.Project](tx, project, "id = :id", lit.P{"id": id})+ if err != nil {+ return nil, err+ }+ return project, nil+}++func (p *projectRepository) Delete(tx *sql.Tx, id uuid.UUID) error {+ related := []string{+ "notification_rules",+ "notification_channels",+ "widget_groups",+ "source_maps",+ "metric_registry",+ }+ for _, table := range related {+ if err := lit.DeleteNamed(db.Driver, tx, "DELETE FROM "+table+" WHERE project_id = :project_id", lit.P{"project_id": id}); err != nil {+ return fmt.Errorf("deleting %s: %w", table, err)+ }+ }+ return lit.DeleteNamed(db.Driver, tx, "DELETE FROM projects WHERE id = :id", lit.P{"id": id})+}++func (p *projectRepository) FindBySourceMapToken(tx *sql.Tx, token string) (*models.Project, error) {+ return lit.SelectSingleNamed[models.Project](+ tx,+ "SELECT id, name, token, framework, organization_id, created_at, source_map_token, drop_healthy_healthchecks, healthcheck_paths, profile_label_allowlist FROM projects WHERE source_map_token = :smt",+ lit.P{"smt": token},+ )+}++func generateSecureToken() string {+ id := uuid.New()+ return strings.ReplaceAll(id.String(), "-", "")+}++func frameworkRequiresSymbolUpload(framework string) bool {+ switch framework {+ case "ios":+ return true+ default:+ return false+ }+}++var ProjectRepository = projectRepository{}diff --git a/backend/app/repositories/transactional/sqlite/refresh_token.repository.go b/backend/app/repositories/transactional/sqlite/refresh_token.repository.gonew file mode 100644index 00000000..65473339--- /dev/null+++ b/backend/app/repositories/transactional/sqlite/refresh_token.repository.go@@ -0,0 +1,141 @@+//go:build !transactional_pg++package sqlite++import (+ "database/sql"+ "errors"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional/shared"+ "time"++ "github.com/tracewayapp/lit/v2"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"+)++type refreshTokenRepository struct{}++func (r *refreshTokenRepository) Insert(ex lit.Executor, token, familyId string, userId int, clientId string, expiresAt time.Time) error {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ `INSERT INTO refresh_tokens (token_hash, family_id, user_id, client_id, revoked, used, expires_at, created_at)+ VALUES (:hash, :family, :user_id, :client_id, :revoked, :used, :expires_at, :created_at)`,+ lit.P{+ "hash": shared.HashAuthToken(token),+ "family": familyId,+ "user_id": userId,+ "client_id": clientId,+ "revoked": false,+ "used": false,+ "expires_at": shared.FormatAuthTime(expiresAt),+ "created_at": shared.FormatAuthTime(time.Now()),+ },+ )+ if err != nil {+ return err+ }+ _, err = ex.Exec(query, args...)+ return err+}++func (r *refreshTokenRepository) FindByToken(ex lit.Executor, token string) (*models.RefreshToken, error) {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ "SELECT token_hash, family_id, user_id, client_id, revoked, used, used_at, expires_at, created_at FROM refresh_tokens WHERE token_hash = :hash",+ lit.P{"hash": shared.HashAuthToken(token)},+ )+ if err != nil {+ return nil, err+ }++ var (+ t models.RefreshToken+ usedAt sql.NullString+ expiresAt string+ createdAt string+ )+ err = ex.QueryRow(query, args...).Scan(&t.TokenHash, &t.FamilyId, &t.UserId, &t.ClientId, &t.Revoked, &t.Used, &usedAt, &expiresAt, &createdAt)+ if errors.Is(err, sql.ErrNoRows) {+ return nil, nil+ }+ if err != nil {+ return nil, err+ }++ if t.UsedAt, err = shared.ParseNullableAuthTime(usedAt); err != nil {+ return nil, err+ }+ if t.ExpiresAt, err = shared.ParseAuthTime(expiresAt); err != nil {+ return nil, err+ }+ if t.CreatedAt, err = shared.ParseAuthTime(createdAt); err != nil {+ return nil, err+ }+ return &t, nil+}++// MarkUsedIfUnused atomically flips the token to used, but only if it is still+// unused and not revoked. The rows-affected result is the concurrency guard: a+// return of 0 means another request already consumed (or revoked) this token,+// which is how RotateRefresh distinguishes a benign concurrent retry from a+// genuine replay of an already-rotated token.+func (r *refreshTokenRepository) MarkUsedIfUnused(ex lit.Executor, token string, usedAt time.Time) (int64, error) {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ "UPDATE refresh_tokens SET used = :used, used_at = :used_at WHERE token_hash = :hash AND used = :active AND revoked = :active",+ lit.P{"used": true, "used_at": shared.FormatAuthTime(usedAt), "hash": shared.HashAuthToken(token), "active": false},+ )+ if err != nil {+ return 0, err+ }+ res, err := ex.Exec(query, args...)+ if err != nil {+ return 0, err+ }+ return res.RowsAffected()+}++func (r *refreshTokenRepository) RevokeFamily(ex lit.Executor, familyId string) error {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ "UPDATE refresh_tokens SET revoked = :revoked WHERE family_id = :family",+ lit.P{"revoked": true, "family": familyId},+ )+ if err != nil {+ return err+ }+ _, err = ex.Exec(query, args...)+ return err+}++// usedRefreshTokenRetention is how long a consumed (rotated) token row is kept+// so a genuine replay can still be detected and revoke its family. Without a+// cap, every rotation would leave a row behind for the full 90-day expiry;+// after a month the row's only value is replay detection for a token an+// attacker can no longer redeem, so it is safe to drop. Revoked rows carry no+// signal at all (the family is already dead) and are dropped immediately,+// matching the PAT prune.+const usedRefreshTokenRetention = 30 * 24 * time.Hour++func (r *refreshTokenRepository) PruneExpired(ex lit.Executor, now time.Time) (int64, error) {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ "DELETE FROM refresh_tokens WHERE expires_at < :cutoff OR revoked = :revoked OR (used = :used AND used_at < :used_cutoff)",+ lit.P{+ "cutoff": shared.FormatAuthTime(now),+ "revoked": true,+ "used": true,+ "used_cutoff": shared.FormatAuthTime(now.Add(-usedRefreshTokenRetention)),+ },+ )+ if err != nil {+ return 0, err+ }+ res, err := ex.Exec(query, args...)+ if err != nil {+ return 0, err+ }+ return res.RowsAffected()+}++var RefreshTokenRepository = refreshTokenRepository{}diff --git a/backend/app/repositories/transactional/sqlite/user.repository.go b/backend/app/repositories/transactional/sqlite/user.repository.gonew file mode 100644index 00000000..a3b9fe6f--- /dev/null+++ b/backend/app/repositories/transactional/sqlite/user.repository.go@@ -0,0 +1,173 @@+//go:build !transactional_pg++package sqlite++import (+ "database/sql"+ "time"++ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"++ "github.com/tracewayapp/lit/v2"+)++type userRepository struct{}++const userColumns = "id, email, name, password, created_at, oauth_provider, oauth_user_id, avatar_url"++func (r *userRepository) FindByEmail(tx *sql.Tx, email string) (*models.User, error) {+ return lit.SelectSingleNamed[models.User](+ tx,+ "SELECT "+userColumns+" FROM users WHERE email = :email",+ lit.P{"email": email},+ )+}++func (r *userRepository) FindByEmailIgnoreCase(tx *sql.Tx, email string) (*models.User, error) {+ return lit.SelectSingleNamed[models.User](+ tx,+ "SELECT "+userColumns+" FROM users WHERE LOWER(email) = LOWER(:email)",+ lit.P{"email": email},+ )+}++func (r *userRepository) FindById(tx *sql.Tx, id int) (*models.User, error) {+ return lit.SelectSingleNamed[models.User](+ tx,+ "SELECT "+userColumns+" FROM users WHERE id = :id",+ lit.P{"id": id},+ )+}++func (r *userRepository) FindByOAuth(tx *sql.Tx, provider string, providerUserId string) (*models.User, error) {+ return lit.SelectSingleNamed[models.User](+ tx,+ "SELECT "+userColumns+" FROM users WHERE oauth_provider = :provider AND oauth_user_id = :uid",+ lit.P{"provider": provider, "uid": providerUserId},+ )+}++func (r *userRepository) Create(tx *sql.Tx, email string, name string, hashedPassword string) (*models.User, error) {+ user := &models.User{+ Email: email,+ Name: name,+ Password: hashedPassword,+ CreatedAt: time.Now().UTC(),+ }++ id, err := lit.Insert(tx, user)+ if err != nil {+ return nil, err+ }+ user.Id = id++ return user, nil+}++func (r *userRepository) CreateOAuth(tx *sql.Tx, email, name, provider, providerUserId, avatarUrl string) (*models.User, error) {+ var avatar *string+ if avatarUrl != "" {+ avatar = &avatarUrl+ }+ user := &models.User{+ Email: email,+ Name: name,+ Password: "",+ CreatedAt: time.Now().UTC(),+ OauthProvider: &provider,+ OauthUserId: &providerUserId,+ AvatarUrl: avatar,+ }++ id, err := lit.Insert(tx, user)+ if err != nil {+ return nil, err+ }+ user.Id = id++ return user, nil+}++func (r *userRepository) LinkOAuth(tx *sql.Tx, userId int, provider, providerUserId, avatarUrl string) error {+ q, a, err := lit.ParseNamedQuery(+ db.Driver,+ "UPDATE users SET oauth_provider = :provider, oauth_user_id = :uid, avatar_url = COALESCE(:avatar, avatar_url) WHERE id = :id",+ lit.P{+ "provider": provider,+ "uid": providerUserId,+ "avatar": nullIfEmpty(avatarUrl),+ "id": userId,+ },+ )+ if err != nil {+ return err+ }+ return lit.UpdateNative(tx, q, a...)+}++func nullIfEmpty(s string) any {+ if s == "" {+ return nil+ }+ return s+}++func (r *userRepository) EmailExists(tx *sql.Tx, email string) (bool, error) {+ user, err := r.FindByEmail(tx, email)+ if err != nil {+ return false, err+ }+ return user != nil, nil+}++func (r *userRepository) SetPasswordResetToken(tx *sql.Tx, userId int, token string, expiresAt time.Time) error {+ q, a, err := lit.ParseNamedQuery(+ db.Driver,+ "UPDATE users SET password_reset_token = :token, password_reset_expires_at = :expires, password_reset_requested_at = :now WHERE id = :id",+ lit.P{+ "token": token,+ "expires": expiresAt,+ "now": time.Now(),+ "id": userId,+ },+ )+ if err != nil {+ return err+ }+ return lit.UpdateNative(tx, q, a...)+}++func (r *userRepository) ClearPasswordResetToken(tx *sql.Tx, userId int) error {+ q, a, err := lit.ParseNamedQuery(db.Driver, "UPDATE users SET password_reset_token = NULL, password_reset_expires_at = NULL, password_reset_requested_at = NULL WHERE id = :id", lit.P{"id": userId})+ if err != nil {+ return err+ }+ _, err = tx.Exec(q, a...)+ return err+}++func (r *userRepository) FindByPasswordResetToken(tx *sql.Tx, token string) (*models.User, error) {+ return lit.SelectSingleNamed[models.User](+ tx,+ "SELECT "+userColumns+", password_reset_token, password_reset_expires_at, password_reset_requested_at FROM users WHERE password_reset_token = :token",+ lit.P{"token": token},+ )+}++func (r *userRepository) UpdatePassword(tx *sql.Tx, userId int, hashedPassword string) error {+ q, a, err := lit.ParseNamedQuery(+ db.Driver,+ "UPDATE users SET password = :password WHERE id = :id",+ lit.P{+ "password": hashedPassword,+ "id": userId,+ },+ )+ if err != nil {+ return err+ }+ return lit.UpdateNative(tx, q, a...)+}++var UserRepository = userRepository{}diff --git a/backend/app/repositories/transactional/sqlite/widget_group.repository.go b/backend/app/repositories/transactional/sqlite/widget_group.repository.gonew file mode 100644index 00000000..dd4b7d89--- /dev/null+++ b/backend/app/repositories/transactional/sqlite/widget_group.repository.go@@ -0,0 +1,175 @@+//go:build !transactional_pg++package sqlite++import (+ "database/sql"++ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"++ "github.com/google/uuid"+ "github.com/tracewayapp/lit/v2"+)++type widgetGroupRepository struct{}++func (r *widgetGroupRepository) FindByProject(tx *sql.Tx, projectId uuid.UUID) ([]*models.WidgetGroup, error) {+ return lit.SelectNamed[models.WidgetGroup](+ tx,+ "SELECT id, project_id, name, description, is_default, created_by, created_at, updated_at FROM widget_groups WHERE project_id = :project_id ORDER BY is_default DESC, name ASC",+ lit.P{"project_id": projectId},+ )+}++func (r *widgetGroupRepository) FindById(tx *sql.Tx, id int) (*models.WidgetGroup, error) {+ return lit.SelectSingleNamed[models.WidgetGroup](+ tx,+ "SELECT id, project_id, name, description, is_default, created_by, created_at, updated_at FROM widget_groups WHERE id = :id",+ lit.P{"id": id},+ )+}++func (r *widgetGroupRepository) Create(tx *sql.Tx, group *models.WidgetGroup) (int, error) {+ return lit.Insert[models.WidgetGroup](tx, group)+}++func (r *widgetGroupRepository) Update(tx *sql.Tx, group *models.WidgetGroup) error {+ return lit.UpdateNamed(tx, group, "id = :id", lit.P{"id": group.Id})+}++func (r *widgetGroupRepository) Delete(tx *sql.Tx, id int) error {+ return lit.DeleteNamed(db.Driver, tx, "DELETE FROM widget_groups WHERE id = :id", lit.P{"id": id})+}++func (r *widgetGroupRepository) FindWidgetsByGroup(tx *sql.Tx, widgetGroupId int) ([]*models.WidgetGroupWidget, error) {+ return lit.SelectNamed[models.WidgetGroupWidget](+ tx,+ "SELECT id, widget_group_id, title, widget_type, config, position, created_at, updated_at FROM widget_group_widgets WHERE widget_group_id = :wg_id ORDER BY position ASC",+ lit.P{"wg_id": widgetGroupId},+ )+}++func (r *widgetGroupRepository) FindWidgetsByGroupWithStar(tx *sql.Tx, widgetGroupId int) ([]*models.WidgetGroupWidgetWithStar, error) {+ return lit.SelectNamed[models.WidgetGroupWidgetWithStar](+ tx,+ `SELECT wgw.id, wgw.widget_group_id, wgw.title, wgw.widget_type, wgw.config, wgw.position,+ (sw.id IS NOT NULL) AS is_starred,+ wgw.created_at, wgw.updated_at+ FROM widget_group_widgets wgw+ LEFT JOIN starred_widgets sw ON sw.widget_id = wgw.id+ WHERE wgw.widget_group_id = :wg_id+ ORDER BY wgw.position ASC`,+ lit.P{"wg_id": widgetGroupId},+ )+}++func (r *widgetGroupRepository) FindWidgetById(tx *sql.Tx, id int) (*models.WidgetGroupWidget, error) {+ return lit.SelectSingleNamed[models.WidgetGroupWidget](+ tx,+ "SELECT id, widget_group_id, title, widget_type, config, position, created_at, updated_at FROM widget_group_widgets WHERE id = :id",+ lit.P{"id": id},+ )+}++func (r *widgetGroupRepository) FindStarredWidgetsByProject(tx *sql.Tx, projectId uuid.UUID) ([]*models.StarredWidgetWithHome, error) {+ return lit.SelectNamed[models.StarredWidgetWithHome](+ tx,+ `SELECT wgw.id, wgw.widget_group_id, wgw.title, wgw.widget_type, wgw.config, wgw.position,+ sw.position AS home_position, sw.col_span AS home_col_span, sw.size AS home_size,+ wgw.created_at, wgw.updated_at+ FROM starred_widgets sw+ JOIN widget_group_widgets wgw ON wgw.id = sw.widget_id+ JOIN widget_groups wg ON wg.id = wgw.widget_group_id+ WHERE wg.project_id = :project_id+ ORDER BY sw.position ASC, sw.id ASC`,+ lit.P{"project_id": projectId},+ )+}++func (r *widgetGroupRepository) FindStarredByProject(tx *sql.Tx, projectId uuid.UUID) ([]*models.StarredWidget, error) {+ return lit.SelectNamed[models.StarredWidget](+ tx,+ `SELECT sw.id, sw.widget_id, sw.position, sw.col_span, sw.size, sw.created_at+ FROM starred_widgets sw+ JOIN widget_group_widgets wgw ON wgw.id = sw.widget_id+ JOIN widget_groups wg ON wg.id = wgw.widget_group_id+ WHERE wg.project_id = :project_id+ ORDER BY sw.position ASC, sw.id ASC`,+ lit.P{"project_id": projectId},+ )+}++func (r *widgetGroupRepository) FindStarredByWidgetId(tx *sql.Tx, projectId uuid.UUID, widgetId int) (*models.StarredWidget, error) {+ return lit.SelectSingleNamed[models.StarredWidget](+ tx,+ `SELECT sw.id, sw.widget_id, sw.position, sw.col_span, sw.size, sw.created_at+ FROM starred_widgets sw+ JOIN widget_group_widgets wgw ON wgw.id = sw.widget_id+ JOIN widget_groups wg ON wg.id = wgw.widget_group_id+ WHERE sw.widget_id = :widget_id AND wg.project_id = :project_id`,+ lit.P{"widget_id": widgetId, "project_id": projectId},+ )+}++func (r *widgetGroupRepository) CreateStarred(tx *sql.Tx, starred *models.StarredWidget) error {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ `INSERT INTO starred_widgets (widget_id, position, col_span, size, created_at)+ VALUES (:widget_id, :position, :col_span, :size, :created_at)+ ON CONFLICT (widget_id) DO NOTHING`,+ lit.P{+ "widget_id": starred.WidgetId,+ "position": starred.Position,+ "col_span": starred.ColSpan,+ "size": starred.Size,+ "created_at": starred.CreatedAt,+ },+ )+ if err != nil {+ return err+ }+ return lit.UpdateNative(tx, query, args...)+}++func (r *widgetGroupRepository) UpdateStarred(tx *sql.Tx, starred *models.StarredWidget) error {+ return lit.UpdateNamed(tx, starred, "id = :id", lit.P{"id": starred.Id})+}++func (r *widgetGroupRepository) DeleteStarredByWidgetId(tx *sql.Tx, widgetId int) error {+ return lit.DeleteNamed(db.Driver, tx, "DELETE FROM starred_widgets WHERE widget_id = :widget_id", lit.P{"widget_id": widgetId})+}++func (r *widgetGroupRepository) DeleteStarredByGroup(tx *sql.Tx, widgetGroupId int) error {+ return lit.DeleteNamed(+ db.Driver, tx,+ "DELETE FROM starred_widgets WHERE widget_id IN (SELECT id FROM widget_group_widgets WHERE widget_group_id = :wg_id)",+ lit.P{"wg_id": widgetGroupId},+ )+}++func (r *widgetGroupRepository) CreateWidget(tx *sql.Tx, widget *models.WidgetGroupWidget) (int, error) {+ return lit.Insert[models.WidgetGroupWidget](tx, widget)+}++func (r *widgetGroupRepository) UpdateWidget(tx *sql.Tx, widget *models.WidgetGroupWidget) error {+ return lit.UpdateNamed(tx, widget, "id = :id", lit.P{"id": widget.Id})+}++func (r *widgetGroupRepository) DeleteWidget(tx *sql.Tx, id int) error {+ return lit.DeleteNamed(db.Driver, tx, "DELETE FROM widget_group_widgets WHERE id = :id", lit.P{"id": id})+}++// DeleteWidgetsByGroup removes every widget belonging to the group. Use this+// before WidgetGroupRepository.Delete so the group + child widgets disappear+// together within the same transaction (rather than relying on the FK cascade+// — explicit is cheaper to audit and makes the SQL log self-explanatory).+func (r *widgetGroupRepository) DeleteWidgetsByGroup(tx *sql.Tx, widgetGroupId int) error {+ return lit.DeleteNamed(+ db.Driver, tx,+ "DELETE FROM widget_group_widgets WHERE widget_group_id = :wg_id",+ lit.P{"wg_id": widgetGroupId},+ )+}++var WidgetGroupRepository = widgetGroupRepository{}diff --git a/backend/app/repositories/transactional/testhelper_test.go b/backend/app/repositories/transactional/testhelper_test.gonew file mode 100644index 00000000..bc41151c--- /dev/null+++ b/backend/app/repositories/transactional/testhelper_test.go@@ -0,0 +1,38 @@+//go:build !transactional_pg++package transactional++import (+ "database/sql"+ "testing"++ "github.com/tracewayapp/lit/v2"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"+ _ "modernc.org/sqlite"+)++func setupTestDB(t *testing.T) {+ t.Helper()++ mainDB, err := sql.Open("sqlite", ":memory:")+ if err != nil {+ t.Fatalf("failed to open in-memory sqlite (main): %v", err)+ }+ mainDB.SetMaxOpenConns(1)+ if _, err := mainDB.Exec("PRAGMA foreign_keys = ON"); err != nil {+ t.Fatalf("failed to enable foreign keys: %v", err)+ }+ if _, err := mainDB.Exec("PRAGMA journal_mode = WAL"); err != nil {+ t.Fatalf("failed to set WAL mode: %v", err)+ }++ db.DB = mainDB+ db.Driver = lit.SQLite++ models.Init(db.Driver)++ t.Cleanup(func() {+ mainDB.Close()+ })+}diff --git a/backend/app/repositories/transactional/transactional_pg.go b/backend/app/repositories/transactional/transactional_pg.gonew file mode 100644index 00000000..75a0e0c5--- /dev/null+++ b/backend/app/repositories/transactional/transactional_pg.go@@ -0,0 +1,22 @@+//go:build transactional_pg++package transactional++import pgrepo "github.com/tracewayapp/traceway/backend/app/repositories/transactional/pg"++var (+ AuthorizationCodeRepository = pgrepo.AuthorizationCodeRepository+ DeviceAuthorizationRepository = pgrepo.DeviceAuthorizationRepository+ InvitationRepository = pgrepo.InvitationRepository+ MetricRegistryRepository = pgrepo.MetricRegistryRepository+ NotificationChannelRepository = pgrepo.NotificationChannelRepository+ NotificationRuleRepository = pgrepo.NotificationRuleRepository+ OAuthSessionRepository = pgrepo.OAuthSessionRepository+ OauthClientRepository = pgrepo.OauthClientRepository+ OrganizationRepository = pgrepo.OrganizationRepository+ PersonalAccessTokenRepository = pgrepo.PersonalAccessTokenRepository+ ProjectRepository = pgrepo.ProjectRepository+ RefreshTokenRepository = pgrepo.RefreshTokenRepository+ UserRepository = pgrepo.UserRepository+ WidgetGroupRepository = pgrepo.WidgetGroupRepository+)diff --git a/backend/app/repositories/transactional/transactional_shared.go b/backend/app/repositories/transactional/transactional_shared.gonew file mode 100644index 00000000..1ff4a53c--- /dev/null+++ b/backend/app/repositories/transactional/transactional_shared.go@@ -0,0 +1,10 @@+package transactional++import "github.com/tracewayapp/traceway/backend/app/repositories/transactional/shared"++// Aliases so consumers keep using the transactional package regardless of+// which relational backend is compiled in.+type (+ ActivePAT = shared.ActivePAT+ MetricRegistrationEntry = shared.MetricRegistrationEntry+)diff --git a/backend/app/repositories/transactional/transactional_sqlite.go b/backend/app/repositories/transactional/transactional_sqlite.gonew file mode 100644index 00000000..a7cd9a77--- /dev/null+++ b/backend/app/repositories/transactional/transactional_sqlite.go@@ -0,0 +1,22 @@+//go:build !transactional_pg++package transactional++import sqliterepo "github.com/tracewayapp/traceway/backend/app/repositories/transactional/sqlite"++var (+ AuthorizationCodeRepository = sqliterepo.AuthorizationCodeRepository+ DeviceAuthorizationRepository = sqliterepo.DeviceAuthorizationRepository+ InvitationRepository = sqliterepo.InvitationRepository+ MetricRegistryRepository = sqliterepo.MetricRegistryRepository+ NotificationChannelRepository = sqliterepo.NotificationChannelRepository+ NotificationRuleRepository = sqliterepo.NotificationRuleRepository+ OAuthSessionRepository = sqliterepo.OAuthSessionRepository+ OauthClientRepository = sqliterepo.OauthClientRepository+ OrganizationRepository = sqliterepo.OrganizationRepository+ PersonalAccessTokenRepository = sqliterepo.PersonalAccessTokenRepository+ ProjectRepository = sqliterepo.ProjectRepository+ RefreshTokenRepository = sqliterepo.RefreshTokenRepository+ UserRepository = sqliterepo.UserRepository+ WidgetGroupRepository = sqliterepo.WidgetGroupRepository+)diff --git a/backend/app/retention/auth_tokens.go b/backend/app/retention/auth_tokens.goindex 21947910..b05ed95e 100644--- a/backend/app/retention/auth_tokens.go+++ b/backend/app/retention/auth_tokens.go@@ -5,7 +5,7 @@ import ("database/sql""time"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional")const authTokensPruneInterval = 24 * time.Hour@@ -15,31 +15,31 @@ func startAuthTokensPrune(ctx context.Context) {now := time.Now().UTC()var total int64- n, err := repositories.DeviceAuthorizationRepository.PruneExpired(tx, now)+ n, err := transactional.DeviceAuthorizationRepository.PruneExpired(tx, now)if err != nil {return total, err}total += n- n, err = repositories.RefreshTokenRepository.PruneExpired(tx, now)+ n, err = transactional.RefreshTokenRepository.PruneExpired(tx, now)if err != nil {return total, err}total += n- n, err = repositories.PersonalAccessTokenRepository.PruneExpired(tx, now)+ n, err = transactional.PersonalAccessTokenRepository.PruneExpired(tx, now)if err != nil {return total, err}total += n- n, err = repositories.AuthorizationCodeRepository.PruneExpired(tx, now)+ n, err = transactional.AuthorizationCodeRepository.PruneExpired(tx, now)if err != nil {return total, err}total += n- n, err = repositories.OauthClientRepository.PruneStale(tx, now)+ n, err = transactional.OauthClientRepository.PruneStale(tx, now)if err != nil {return total, err}diff --git a/backend/app/retention/oauth_sessions.go b/backend/app/retention/oauth_sessions.goindex 37dabd60..d44ba1ee 100644--- a/backend/app/retention/oauth_sessions.go+++ b/backend/app/retention/oauth_sessions.go@@ -5,13 +5,13 @@ import ("database/sql""time"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional")const oauthSessionsPruneInterval = 24 * time.Hourfunc startOAuthSessionsPrune(ctx context.Context) {startDBPruneWorker(ctx, "oauth_sessions", oauthSessionsPruneInterval, func(tx *sql.Tx) (int64, error) {- return repositories.OAuthSessionRepository.PruneExpired(tx, time.Now().UTC())+ return transactional.OAuthSessionRepository.PruneExpired(tx, time.Now().UTC())})}diff --git a/backend/app/retention/sqlite.go b/backend/app/retention/sqlite.goindex 0fbbdcc6..627b3ddf 100644--- a/backend/app/retention/sqlite.go+++ b/backend/app/retention/sqlite.go@@ -78,6 +78,12 @@ func runSQLiteRetention(ctx context.Context, days int) {}func reclaimTelemetryDisk(ctx context.Context) {+ if db.IsDuckDBTelemetry() {+ if _, err := db.TelemetryDB.ExecContext(ctx, "CHECKPOINT"); err != nil {+ traceway.CaptureException(fmt.Errorf("retention: telemetry maintenance %q failed: %w", "CHECKPOINT", err))+ }+ return+ }for _, stmt := range []string{"PRAGMA incremental_vacuum","PRAGMA optimize",diff --git a/backend/app/retention/sqlite_test.go b/backend/app/retention/sqlite_test.goindex b1c89c0f..c1d6ca3c 100644--- a/backend/app/retention/sqlite_test.go+++ b/backend/app/retention/sqlite_test.go@@ -1,4 +1,4 @@-//go:build !pgch+//go:build !telemetry_chpackage retentiondiff --git a/backend/app/services/authserver/authcode.go b/backend/app/services/authserver/authcode.goindex 90f5a8df..bf757c3c 100644--- a/backend/app/services/authserver/authcode.go+++ b/backend/app/services/authserver/authcode.go@@ -19,7 +19,7 @@ import ("github.com/tracewayapp/traceway/backend/app/db""github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional")var (@@ -52,7 +52,7 @@ func RegisterClient(tx *sql.Tx, name string, redirectURIs []string) (*models.OauRedirectUris: redirectURIs,CreatedAt: time.Now().UTC(),}- if err := repositories.OauthClientRepository.Create(tx, client); err != nil {+ if err := transactional.OauthClientRepository.Create(tx, client); err != nil {return nil, err}return client, nil@@ -170,11 +170,11 @@ func ApproveAuthorization(tx *sql.Tx, userId int, req models.AuthorizeApproveReqreturn "", err}- if _, err := repositories.AuthorizationCodeRepository.PruneExpired(tx, time.Now()); err != nil {+ if _, err := transactional.AuthorizationCodeRepository.PruneExpired(tx, time.Now()); err != nil {return "", err}code := newOpaqueToken("twa_")- if err := repositories.AuthorizationCodeRepository.Create(tx, code, client.Id, userId, req.RedirectUri, req.CodeChallenge, time.Now().Add(authCodeTTL)); err != nil {+ if err := transactional.AuthorizationCodeRepository.Create(tx, code, client.Id, userId, req.RedirectUri, req.CodeChallenge, time.Now().Add(authCodeTTL)); err != nil {return "", err}return appendRedirectParams(req.RedirectUri, url.Values{"code": {code}}, req.State), nil@@ -191,7 +191,7 @@ func validateAuthorizeTarget(ex lit.Executor, clientId, redirectUri string) (*moif clientId == "" {return nil, ErrUnknownClient}- client, err := repositories.OauthClientRepository.FindById(ex, clientId)+ client, err := transactional.OauthClientRepository.FindById(ex, clientId)if err != nil {return nil, err}@@ -228,14 +228,14 @@ func RedeemAuthorizationCode(clientId, code, verifier, redirectUri, resource, isgrantErr error}out, err := db.ExecuteTransaction(func(tx *sql.Tx) (redeemOutcome, error) {- ac, err := repositories.AuthorizationCodeRepository.FindByCode(tx, code)+ ac, err := transactional.AuthorizationCodeRepository.FindByCode(tx, code)if err != nil {return redeemOutcome{}, err}if ac == nil {return redeemOutcome{grantErr: ErrInvalidGrant}, nil}- deleted, err := repositories.AuthorizationCodeRepository.Delete(tx, code)+ deleted, err := transactional.AuthorizationCodeRepository.Delete(tx, code)if err != nil {return redeemOutcome{}, err}@@ -245,7 +245,7 @@ func RedeemAuthorizationCode(clientId, code, verifier, redirectUri, resource, isif time.Now().After(ac.ExpiresAt) || ac.ClientId != clientId || ac.RedirectUri != redirectUri || !verifyPKCE(ac.CodeChallenge, verifier) {return redeemOutcome{grantErr: ErrInvalidGrant}, nil}- user, err := repositories.UserRepository.FindById(tx, ac.UserId)+ user, err := transactional.UserRepository.FindById(tx, ac.UserId)if err != nil {return redeemOutcome{}, err}diff --git a/backend/app/services/authserver/authcode_test.go b/backend/app/services/authserver/authcode_test.goindex 509b7807..45d1ef1d 100644--- a/backend/app/services/authserver/authcode_test.go+++ b/backend/app/services/authserver/authcode_test.go@@ -1,4 +1,4 @@-//go:build !pgch+//go:build !telemetry_ch && !telemetry_duckdbpackage authserver@@ -14,7 +14,7 @@ import ("github.com/tracewayapp/traceway/backend/app/db""github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional")const testVerifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"@@ -89,7 +89,7 @@ func TestRegisterClient_validation(t *testing.T) {}client := registerTestClient(t, "https://claude.ai/api/mcp/auth_callback", "http://localhost:3000/cb", "cursor://anysphere.cursor-mcp/callback")- loaded, err := repositories.OauthClientRepository.FindById(db.DB, client.Id)+ loaded, err := transactional.OauthClientRepository.FindById(db.DB, client.Id)if err != nil || loaded == nil {t.Fatalf("reload client: %v, %v", loaded, err)}@@ -211,7 +211,7 @@ func TestAuthCode_expiredCodeRejected(t *testing.T) {client := registerTestClient(t)_, err := db.ExecuteTransaction(func(tx *sql.Tx) (struct{}, error) {- return struct{}{}, repositories.AuthorizationCodeRepository.Create(+ return struct{}{}, transactional.AuthorizationCodeRepository.Create(tx, "twa_expired", client.Id, 1, "http://127.0.0.1:8123/callback", testChallenge(testVerifier), time.Now().Add(-time.Minute))})if err != nil {@@ -221,7 +221,7 @@ func TestAuthCode_expiredCodeRejected(t *testing.T) {if _, err := RedeemAuthorizationCode(client.Id, "twa_expired", testVerifier, "http://127.0.0.1:8123/callback", "", ""); !errors.Is(err, ErrInvalidGrant) {t.Fatalf("expired code should be invalid_grant, got %v", err)}- if got, _ := repositories.AuthorizationCodeRepository.FindByCode(db.DB, "twa_expired"); got != nil {+ if got, _ := transactional.AuthorizationCodeRepository.FindByCode(db.DB, "twa_expired"); got != nil {t.Fatal("expired code should be consumed even on a failed exchange")}}@@ -305,22 +305,22 @@ func TestAuthorizationCodeRepository_PruneExpired(t *testing.T) {client := registerTestClient(t)_, err := db.ExecuteTransaction(func(tx *sql.Tx) (struct{}, error) {- if err := repositories.AuthorizationCodeRepository.Create(tx, "twa_live", client.Id, 1, "http://127.0.0.1:1/cb", testChallenge(testVerifier), time.Now().Add(time.Minute)); err != nil {+ if err := transactional.AuthorizationCodeRepository.Create(tx, "twa_live", client.Id, 1, "http://127.0.0.1:1/cb", testChallenge(testVerifier), time.Now().Add(time.Minute)); err != nil {return struct{}{}, err}- return struct{}{}, repositories.AuthorizationCodeRepository.Create(tx, "twa_dead", client.Id, 1, "http://127.0.0.1:1/cb", testChallenge(testVerifier), time.Now().Add(-time.Minute))+ return struct{}{}, transactional.AuthorizationCodeRepository.Create(tx, "twa_dead", client.Id, 1, "http://127.0.0.1:1/cb", testChallenge(testVerifier), time.Now().Add(-time.Minute))})if err != nil {t.Fatalf("seed codes: %v", err)}pruned, err := db.ExecuteTransaction(func(tx *sql.Tx) (int64, error) {- return repositories.AuthorizationCodeRepository.PruneExpired(tx, time.Now())+ return transactional.AuthorizationCodeRepository.PruneExpired(tx, time.Now())})if err != nil || pruned != 1 {t.Fatalf("prune = %d, %v; want 1, nil", pruned, err)}- if live, _ := repositories.AuthorizationCodeRepository.FindByCode(db.DB, "twa_live"); live == nil {+ if live, _ := transactional.AuthorizationCodeRepository.FindByCode(db.DB, "twa_live"); live == nil {t.Fatal("live code should survive the prune")}}diff --git a/backend/app/services/authserver/authserver_test.go b/backend/app/services/authserver/authserver_test.goindex 2fc2d684..3db448e3 100644--- a/backend/app/services/authserver/authserver_test.go+++ b/backend/app/services/authserver/authserver_test.go@@ -1,4 +1,4 @@-//go:build !pgch+//go:build !telemetry_ch && !telemetry_duckdbpackage authserver@@ -13,7 +13,7 @@ import ("github.com/tracewayapp/traceway/backend/app/db""github.com/tracewayapp/traceway/backend/app/migrations""github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional""github.com/tracewayapp/traceway/backend/app/services"_ "modernc.org/sqlite"@@ -60,7 +60,7 @@ func setupAuthDB(t *testing.T) {func insertRefresh(t *testing.T, token, family string) {t.Helper()- if err := repositories.RefreshTokenRepository.Insert(db.DB, token, family, 1, cliClientID, time.Now().Add(time.Hour)); err != nil {+ if err := transactional.RefreshTokenRepository.Insert(db.DB, token, family, 1, cliClientID, time.Now().Add(time.Hour)); err != nil {t.Fatalf("insert refresh token: %v", err)}}@@ -80,11 +80,11 @@ func TestRotateRefresh_sequentialRotation(t *testing.T) {t.Fatal("expected an access token")}- old, _ := repositories.RefreshTokenRepository.FindByToken(db.DB, "twr_seq")+ old, _ := transactional.RefreshTokenRepository.FindByToken(db.DB, "twr_seq")if old == nil || !old.Used {t.Fatalf("presented token should be marked used, got %+v", old)}- fresh, _ := repositories.RefreshTokenRepository.FindByToken(db.DB, ts.RefreshToken)+ fresh, _ := transactional.RefreshTokenRepository.FindByToken(db.DB, ts.RefreshToken)if fresh == nil || fresh.Used || fresh.Revoked || fresh.FamilyId != "fam-seq" {t.Fatalf("rotated token should be live in the same family, got %+v", fresh)}@@ -96,7 +96,7 @@ func TestRotateRefresh_replayOutsideGraceRevokesFamily(t *testing.T) {insertRefresh(t, "twr_sibling", "fam-old")// Simulate a token consumed well outside the reuse-grace window.- if _, err := repositories.RefreshTokenRepository.MarkUsedIfUnused(db.DB, "twr_old", time.Now().Add(-time.Hour)); err != nil {+ if _, err := transactional.RefreshTokenRepository.MarkUsedIfUnused(db.DB, "twr_old", time.Now().Add(-time.Hour)); err != nil {t.Fatalf("mark used: %v", err)}@@ -104,7 +104,7 @@ func TestRotateRefresh_replayOutsideGraceRevokesFamily(t *testing.T) {t.Fatalf("expected ErrInvalidGrant, got %v", err)}- sib, _ := repositories.RefreshTokenRepository.FindByToken(db.DB, "twr_sibling")+ sib, _ := transactional.RefreshTokenRepository.FindByToken(db.DB, "twr_sibling")if sib == nil || !sib.Revoked {t.Fatalf("genuine replay must revoke the whole family, sibling = %+v", sib)}@@ -116,7 +116,7 @@ func TestRotateRefresh_concurrentWithinGraceKeepsFamily(t *testing.T) {insertRefresh(t, "twr_winner", "fam-race")// The racing request already consumed the token just now (within grace).- if _, err := repositories.RefreshTokenRepository.MarkUsedIfUnused(db.DB, "twr_race", time.Now()); err != nil {+ if _, err := transactional.RefreshTokenRepository.MarkUsedIfUnused(db.DB, "twr_race", time.Now()); err != nil {t.Fatalf("mark used: %v", err)}@@ -124,7 +124,7 @@ func TestRotateRefresh_concurrentWithinGraceKeepsFamily(t *testing.T) {t.Fatalf("expected ErrInvalidGrant, got %v", err)}- winner, _ := repositories.RefreshTokenRepository.FindByToken(db.DB, "twr_winner")+ winner, _ := transactional.RefreshTokenRepository.FindByToken(db.DB, "twr_winner")if winner == nil || winner.Revoked {t.Fatalf("benign concurrent retry must NOT revoke the family, winner = %+v", winner)}@@ -150,7 +150,7 @@ func TestRotateRefresh_lostResponseReplaysTokenSetWithinGrace(t *testing.T) {t.Fatalf("grace-window retry must replay the rotated token set, got %+v want %+v", second, first)}- winner, _ := repositories.RefreshTokenRepository.FindByToken(db.DB, first.RefreshToken)+ winner, _ := transactional.RefreshTokenRepository.FindByToken(db.DB, first.RefreshToken)if winner == nil || winner.Revoked {t.Fatalf("grace-window retry must not revoke the family, winner = %+v", winner)}@@ -170,7 +170,7 @@ func TestCreateDeviceAuth_unknownClientRejected(t *testing.T) {func TestApprove_expiredCodeRejected(t *testing.T) {setupAuthDB(t)- if err := repositories.DeviceAuthorizationRepository.Create(db.DB, "dev-exp", "CCCC-DDDD", cliClientID, 5, time.Now().Add(-time.Minute)); err != nil {+ if err := transactional.DeviceAuthorizationRepository.Create(db.DB, "dev-exp", "CCCC-DDDD", cliClientID, 5, time.Now().Add(-time.Minute)); err != nil {t.Fatalf("create device auth: %v", err)}@@ -188,7 +188,7 @@ func TestApprove_expiredCodeRejected(t *testing.T) {func TestApprove_lowercaseUserCode(t *testing.T) {setupAuthDB(t)- if err := repositories.DeviceAuthorizationRepository.Create(db.DB, "dev-lc", "EEEE-FFFF", cliClientID, 5, time.Now().Add(deviceCodeTTL)); err != nil {+ if err := transactional.DeviceAuthorizationRepository.Create(db.DB, "dev-lc", "EEEE-FFFF", cliClientID, 5, time.Now().Add(deviceCodeTTL)); err != nil {t.Fatalf("create device auth: %v", err)}@@ -204,7 +204,7 @@ func TestApprove_lowercaseUserCode(t *testing.T) {t.Fatalf("commit: %v", err)}- da, _ := repositories.DeviceAuthorizationRepository.FindByUserCode(db.DB, "EEEE-FFFF")+ da, _ := transactional.DeviceAuthorizationRepository.FindByUserCode(db.DB, "EEEE-FFFF")if da == nil || da.Status != "approved" {t.Fatalf("code should be approved, got %+v", da)}@@ -217,21 +217,21 @@ func TestRefreshTokenRepository_PruneExpired(t *testing.T) {insertRefresh(t, "twr_recent_used", "fam-prune")insertRefresh(t, "twr_old_used", "fam-prune")insertRefresh(t, "twr_revoked", "fam-dead")- if err := repositories.RefreshTokenRepository.Insert(db.DB, "twr_expired", "fam-prune", 1, cliClientID, time.Now().Add(-time.Hour)); err != nil {+ if err := transactional.RefreshTokenRepository.Insert(db.DB, "twr_expired", "fam-prune", 1, cliClientID, time.Now().Add(-time.Hour)); err != nil {t.Fatalf("insert expired: %v", err)}- if _, err := repositories.RefreshTokenRepository.MarkUsedIfUnused(db.DB, "twr_recent_used", time.Now()); err != nil {+ if _, err := transactional.RefreshTokenRepository.MarkUsedIfUnused(db.DB, "twr_recent_used", time.Now()); err != nil {t.Fatalf("mark used: %v", err)}- if _, err := repositories.RefreshTokenRepository.MarkUsedIfUnused(db.DB, "twr_old_used", time.Now().Add(-31*24*time.Hour)); err != nil {+ if _, err := transactional.RefreshTokenRepository.MarkUsedIfUnused(db.DB, "twr_old_used", time.Now().Add(-31*24*time.Hour)); err != nil {t.Fatalf("mark used: %v", err)}- if err := repositories.RefreshTokenRepository.RevokeFamily(db.DB, "fam-dead"); err != nil {+ if err := transactional.RefreshTokenRepository.RevokeFamily(db.DB, "fam-dead"); err != nil {t.Fatalf("revoke family: %v", err)}- n, err := repositories.RefreshTokenRepository.PruneExpired(db.DB, time.Now())+ n, err := transactional.RefreshTokenRepository.PruneExpired(db.DB, time.Now())if err != nil {t.Fatalf("prune: %v", err)}@@ -239,7 +239,7 @@ func TestRefreshTokenRepository_PruneExpired(t *testing.T) {t.Fatalf("prune removed %d rows, want 3 (expired + revoked + anciently used)", n)}for _, tok := range []string{"twr_live", "twr_recent_used"} {- if rt, _ := repositories.RefreshTokenRepository.FindByToken(db.DB, tok); rt == nil {+ if rt, _ := transactional.RefreshTokenRepository.FindByToken(db.DB, tok); rt == nil {t.Fatalf("%s should survive pruning", tok)}}@@ -255,7 +255,7 @@ func TestRevokeByToken_revokesFamily(t *testing.T) {}for _, tok := range []string{"twr_a", "twr_b"} {- rt, _ := repositories.RefreshTokenRepository.FindByToken(db.DB, tok)+ rt, _ := transactional.RefreshTokenRepository.FindByToken(db.DB, tok)if rt == nil || !rt.Revoked {t.Fatalf("logout must revoke the whole family, %s = %+v", tok, rt)}@@ -271,10 +271,10 @@ func TestPollDeviceToken_singleUse(t *testing.T) {const deviceCode = "dev-code"const userCode = "AAAA-BBBB"- if err := repositories.DeviceAuthorizationRepository.Create(db.DB, deviceCode, userCode, cliClientID, 5, time.Now().Add(deviceCodeTTL)); err != nil {+ if err := transactional.DeviceAuthorizationRepository.Create(db.DB, deviceCode, userCode, cliClientID, 5, time.Now().Add(deviceCodeTTL)); err != nil {t.Fatalf("create device auth: %v", err)}- if _, err := repositories.DeviceAuthorizationRepository.Approve(db.DB, userCode, 1); err != nil {+ if _, err := transactional.DeviceAuthorizationRepository.Approve(db.DB, userCode, 1); err != nil {t.Fatalf("approve: %v", err)}@@ -295,11 +295,11 @@ func TestMarkUsedIfUnused_isConditional(t *testing.T) {setupAuthDB(t)insertRefresh(t, "twr_once", "fam-once")- n, err := repositories.RefreshTokenRepository.MarkUsedIfUnused(db.DB, "twr_once", time.Now())+ n, err := transactional.RefreshTokenRepository.MarkUsedIfUnused(db.DB, "twr_once", time.Now())if err != nil || n != 1 {t.Fatalf("first mark = (%d, %v), want (1, nil)", n, err)}- n, err = repositories.RefreshTokenRepository.MarkUsedIfUnused(db.DB, "twr_once", time.Now())+ n, err = transactional.RefreshTokenRepository.MarkUsedIfUnused(db.DB, "twr_once", time.Now())if err != nil || n != 0 {t.Fatalf("second mark = (%d, %v), want (0, nil)", n, err)}@@ -315,14 +315,14 @@ func TestPersonalAccessTokenRepository_PruneExpired(t *testing.T) {t.Fatalf("pat create: %v", err)}}- must(repositories.PersonalAccessTokenRepository.Create(db.DB, "id-active", "twp_active", "twp_active12", 1, "active", nil))- must(repositories.PersonalAccessTokenRepository.Create(db.DB, "id-expired", "twp_expired", "twp_expired1", 1, "expired", &expired))- must(repositories.PersonalAccessTokenRepository.Create(db.DB, "id-revoked", "twp_revoked", "twp_revoked1", 1, "revoked", nil))- if _, err := repositories.PersonalAccessTokenRepository.Revoke(db.DB, "id-revoked", 1); err != nil {+ must(transactional.PersonalAccessTokenRepository.Create(db.DB, "id-active", "twp_active", "twp_active12", 1, "active", nil))+ must(transactional.PersonalAccessTokenRepository.Create(db.DB, "id-expired", "twp_expired", "twp_expired1", 1, "expired", &expired))+ must(transactional.PersonalAccessTokenRepository.Create(db.DB, "id-revoked", "twp_revoked", "twp_revoked1", 1, "revoked", nil))+ if _, err := transactional.PersonalAccessTokenRepository.Revoke(db.DB, "id-revoked", 1); err != nil {t.Fatalf("revoke: %v", err)}- n, err := repositories.PersonalAccessTokenRepository.PruneExpired(db.DB, time.Now())+ n, err := transactional.PersonalAccessTokenRepository.PruneExpired(db.DB, time.Now())if err != nil {t.Fatalf("prune: %v", err)}@@ -330,7 +330,7 @@ func TestPersonalAccessTokenRepository_PruneExpired(t *testing.T) {t.Fatalf("prune removed %d rows, want 2 (expired + revoked)", n)}- active, _ := repositories.PersonalAccessTokenRepository.FindActiveByToken(db.DB, "twp_active")+ active, _ := transactional.PersonalAccessTokenRepository.FindActiveByToken(db.DB, "twp_active")if active == nil {t.Fatal("active PAT should survive pruning")}diff --git a/backend/app/services/authserver/device.go b/backend/app/services/authserver/device.goindex f8a1cbe6..09f3530f 100644--- a/backend/app/services/authserver/device.go+++ b/backend/app/services/authserver/device.go@@ -8,7 +8,7 @@ import ("github.com/tracewayapp/traceway/backend/app/db""github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional")var (@@ -46,10 +46,10 @@ func CreateDeviceAuth(clientId, baseURL string) (*models.DeviceAuthorizeResponse// never accumulate more than one device-code TTL's worth of rows between// the daily prune-worker runs._, err := db.ExecuteTransaction(func(tx *sql.Tx) (struct{}, error) {- if _, err := repositories.DeviceAuthorizationRepository.PruneExpired(tx, time.Now()); err != nil {+ if _, err := transactional.DeviceAuthorizationRepository.PruneExpired(tx, time.Now()); err != nil {return struct{}{}, err}- return struct{}{}, repositories.DeviceAuthorizationRepository.Create(tx, deviceCode, userCode, clientId, interval, time.Now().Add(ttl))+ return struct{}{}, transactional.DeviceAuthorizationRepository.Create(tx, deviceCode, userCode, clientId, interval, time.Now().Add(ttl))})if err != nil {return nil, err@@ -70,7 +70,7 @@ func CreateDeviceAuth(clientId, baseURL string) (*models.DeviceAuthorizeResponse// 400 for normal flow control (pending/slow_down), so it cannot rely on the// request-scoped Transactional middleware (which only commits on 2xx).func PollDeviceToken(deviceCode string) (*models.TokenSetResponse, error) {- da, err := repositories.DeviceAuthorizationRepository.FindByDeviceCode(db.DB, deviceCode)+ da, err := transactional.DeviceAuthorizationRepository.FindByDeviceCode(db.DB, deviceCode)if err != nil {return nil, err}@@ -89,14 +89,14 @@ func PollDeviceToken(deviceCode string) (*models.TokenSetResponse, error) {// Consume the device code first: a device code is single-use, so if// the row is already gone another concurrent poll redeemed it and we// must not mint a second token set for the same code.- deleted, err := repositories.DeviceAuthorizationRepository.Delete(tx, deviceCode)+ deleted, err := transactional.DeviceAuthorizationRepository.Delete(tx, deviceCode)if err != nil {return nil, err}if deleted == 0 {return nil, ErrExpiredToken}- user, err := repositories.UserRepository.FindById(tx, *da.UserId)+ user, err := transactional.UserRepository.FindById(tx, *da.UserId)if err != nil {return nil, err}@@ -113,7 +113,7 @@ func PollDeviceToken(deviceCode string) (*models.TokenSetResponse, error) {interval = da.IntervalSeconds + 5}_, _ = db.ExecuteTransaction(func(tx *sql.Tx) (struct{}, error) {- return struct{}{}, repositories.DeviceAuthorizationRepository.MarkPolled(tx, deviceCode, now, interval)+ return struct{}{}, transactional.DeviceAuthorizationRepository.MarkPolled(tx, deviceCode, now, interval)})if slow {return nil, ErrSlowDown@@ -124,13 +124,13 @@ func PollDeviceToken(deviceCode string) (*models.TokenSetResponse, error) {func Approve(tx *sql.Tx, userCode string, userId int) error {return resolveDevice(tx, userCode, func(canonicalCode string) (int64, error) {- return repositories.DeviceAuthorizationRepository.Approve(tx, canonicalCode, userId)+ return transactional.DeviceAuthorizationRepository.Approve(tx, canonicalCode, userId)})}func Deny(tx *sql.Tx, userCode string) error {return resolveDevice(tx, userCode, func(canonicalCode string) (int64, error) {- return repositories.DeviceAuthorizationRepository.Deny(tx, canonicalCode)+ return transactional.DeviceAuthorizationRepository.Deny(tx, canonicalCode)})}@@ -139,7 +139,7 @@ func Deny(tx *sql.Tx, userCode string) error {// the approval "succeed" would only mislead the user), and so the status// update runs against the stored canonical user code.func resolveDevice(tx *sql.Tx, userCode string, update func(canonicalCode string) (int64, error)) error {- da, err := repositories.DeviceAuthorizationRepository.FindByUserCode(tx, userCode)+ da, err := transactional.DeviceAuthorizationRepository.FindByUserCode(tx, userCode)if err != nil {return err}diff --git a/backend/app/services/authserver/refresh.go b/backend/app/services/authserver/refresh.goindex 3d8d4080..1f82ad03 100644--- a/backend/app/services/authserver/refresh.go+++ b/backend/app/services/authserver/refresh.go@@ -13,7 +13,7 @@ import ("github.com/tracewayapp/traceway/backend/app/db""github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional")var ErrInvalidGrant = errors.New("invalid_grant")@@ -88,7 +88,7 @@ var (// recovers) from a genuine replay of a long-since-rotated token (family// revoked).func RotateRefresh(presented string) (*models.TokenSetResponse, error) {- rt, err := repositories.RefreshTokenRepository.FindByToken(db.DB, presented)+ rt, err := transactional.RefreshTokenRepository.FindByToken(db.DB, presented)if err != nil {return nil, err}@@ -106,7 +106,7 @@ func RotateRefresh(presented string) (*models.TokenSetResponse, error) {}ts, err := db.ExecuteTransaction(func(tx *sql.Tx) (*models.TokenSetResponse, error) {- affected, err := repositories.RefreshTokenRepository.MarkUsedIfUnused(tx, presented, time.Now())+ affected, err := transactional.RefreshTokenRepository.MarkUsedIfUnused(tx, presented, time.Now())if err != nil {return nil, err}@@ -115,7 +115,7 @@ func RotateRefresh(presented string) (*models.TokenSetResponse, error) {// this write. Re-read inside the transaction to classify it, then// signal via a sentinel so the family revoke happens in a committed// transaction rather than this one (which rolls back on error).- current, err := repositories.RefreshTokenRepository.FindByToken(tx, presented)+ current, err := transactional.RefreshTokenRepository.FindByToken(tx, presented)if err != nil {return nil, err}@@ -125,7 +125,7 @@ func RotateRefresh(presented string) (*models.TokenSetResponse, error) {return nil, errReplay}- user, err := repositories.UserRepository.FindById(tx, rt.UserId)+ user, err := transactional.UserRepository.FindById(tx, rt.UserId)if err != nil {return nil, err}@@ -157,7 +157,7 @@ func RotateRefresh(presented string) (*models.TokenSetResponse, error) {// self-manages its transaction because the endpoint may return a non-2xx that// the Transactional middleware would otherwise roll back.func RevokeByToken(presented string) error {- rt, err := repositories.RefreshTokenRepository.FindByToken(db.DB, presented)+ rt, err := transactional.RefreshTokenRepository.FindByToken(db.DB, presented)if err != nil {return err}@@ -165,7 +165,7 @@ func RevokeByToken(presented string) error {return nil}_, err = db.ExecuteTransaction(func(tx *sql.Tx) (struct{}, error) {- return struct{}{}, repositories.RefreshTokenRepository.RevokeFamily(tx, rt.FamilyId)+ return struct{}{}, transactional.RefreshTokenRepository.RevokeFamily(tx, rt.FamilyId)})return err}@@ -177,7 +177,7 @@ func RevokeByToken(presented string) error {// is reported instead of discarded.func revokeFamily(familyId string) {_, err := db.ExecuteTransaction(func(tx *sql.Tx) (struct{}, error) {- return struct{}{}, repositories.RefreshTokenRepository.RevokeFamily(tx, familyId)+ return struct{}{}, transactional.RefreshTokenRepository.RevokeFamily(tx, familyId)})if err != nil {traceway.CaptureException(fmt.Errorf("revoking refresh-token family %s after reuse detection: %w", familyId, err))diff --git a/backend/app/services/authserver/tokens.go b/backend/app/services/authserver/tokens.goindex c82fdd7b..d93205b8 100644--- a/backend/app/services/authserver/tokens.go+++ b/backend/app/services/authserver/tokens.go@@ -9,7 +9,7 @@ import ("github.com/google/uuid""github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional""github.com/tracewayapp/traceway/backend/app/services")@@ -55,7 +55,7 @@ func issueTokenSetWithFamily(tx *sql.Tx, userId int, email, clientId, familyId s}refresh := newOpaqueToken("twr_")- if err := repositories.RefreshTokenRepository.Insert(tx, refresh, familyId, userId, clientId, time.Now().Add(refreshTokenTTL)); err != nil {+ if err := transactional.RefreshTokenRepository.Insert(tx, refresh, familyId, userId, clientId, time.Now().Add(refreshTokenTTL)); err != nil {return nil, err}diff --git a/backend/app/services/metric_registration.service.go b/backend/app/services/metric_registration.service.goindex 23b354db..60cef7fd 100644--- a/backend/app/services/metric_registration.service.go+++ b/backend/app/services/metric_registration.service.go@@ -9,7 +9,7 @@ import ("github.com/tracewayapp/traceway/backend/app/db""github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional")func CollectUniqueMetricNames(points []models.MetricPoint) []string {@@ -26,16 +26,16 @@ func CollectUniqueMetricNames(points []models.MetricPoint) []string {func AutoRegisterMetrics(projectId uuid.UUID, names []string) {_, err := db.ExecuteTransaction(func(tx *sql.Tx) (struct{}, error) {- return struct{}{}, repositories.MetricRegistryRepository.EnsureRegistered(tx, projectId, names)+ return struct{}{}, transactional.MetricRegistryRepository.EnsureRegistered(tx, projectId, names)})if err != nil {traceway.CaptureException(fmt.Errorf("failed to auto-register metrics: %w", err))}}-func AutoRegisterMetricsWithUnits(projectId uuid.UUID, entries []repositories.MetricRegistrationEntry) {+func AutoRegisterMetricsWithUnits(projectId uuid.UUID, entries []transactional.MetricRegistrationEntry) {_, err := db.ExecuteTransaction(func(tx *sql.Tx) (struct{}, error) {- return struct{}{}, repositories.MetricRegistryRepository.EnsureRegisteredWithUnits(tx, projectId, entries)+ return struct{}{}, transactional.MetricRegistryRepository.EnsureRegisteredWithUnits(tx, projectId, entries)})if err != nil {traceway.CaptureException(fmt.Errorf("failed to auto-register OTLP metrics: %w", err))diff --git a/backend/app/services/oauth_session_store.go b/backend/app/services/oauth_session_store.goindex 02d9ade5..a84eef69 100644--- a/backend/app/services/oauth_session_store.go+++ b/backend/app/services/oauth_session_store.go@@ -11,7 +11,7 @@ import ("github.com/gorilla/securecookie""github.com/gorilla/sessions""github.com/tracewayapp/traceway/backend/app/db"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional")// dbSessionStore is a gorilla/sessions.Store backed by the main transactional@@ -67,7 +67,7 @@ func (s *dbSessionStore) New(r *http.Request, name string) (*sessions.Session, eif tx == nil {return session, errNoTransaction}- data, err := repositories.OAuthSessionRepository.Get(tx, id)+ data, err := transactional.OAuthSessionRepository.Get(tx, id)if err != nil || data == nil {return session, nil}@@ -88,7 +88,7 @@ func (s *dbSessionStore) Save(r *http.Request, w http.ResponseWriter, session *sif session.Options != nil && session.Options.MaxAge < 0 {if session.ID != "" {- if err := repositories.OAuthSessionRepository.Delete(tx, session.ID); err != nil {+ if err := transactional.OAuthSessionRepository.Delete(tx, session.ID); err != nil {return err}}@@ -110,7 +110,7 @@ func (s *dbSessionStore) Save(r *http.Request, w http.ResponseWriter, session *s}expires := time.Now().UTC().Add(time.Duration(session.Options.MaxAge) * time.Second)- if err := repositories.OAuthSessionRepository.Save(tx, session.ID, []byte(encoded), expires); err != nil {+ if err := transactional.OAuthSessionRepository.Save(tx, session.ID, []byte(encoded), expires); err != nil {return err}diff --git a/backend/app/sourcemapbackfill/backfill_test.go b/backend/app/sourcemapbackfill/backfill_test.goindex 1353fdbe..ba41c1e3 100644--- a/backend/app/sourcemapbackfill/backfill_test.go+++ b/backend/app/sourcemapbackfill/backfill_test.go@@ -1,4 +1,4 @@-//go:build !pgch+//go:build !telemetry_chpackage sourcemapbackfilldiff --git a/backend/backend b/backend/backenddeleted file mode 100755index 3c38ebfc..00000000Binary files a/backend/backend and /dev/null differdiff --git a/backend/cmd/run.go b/backend/cmd/run.goindex eb095bf2..49ac7feb 100644--- a/backend/cmd/run.go+++ b/backend/cmd/run.go@@ -186,6 +186,7 @@ func Run(opts ...Option) {monitoring.StartClickHouseReporter(ctx)monitoring.StartBackendReporter(ctx)+ monitoring.StartTelemetryDBReporter(ctx)}router.GET("/health", func(c *gin.Context) {diff --git a/backend/cmd/seed.go b/backend/cmd/seed.goindex 903aa792..70db7955 100644--- a/backend/cmd/seed.go+++ b/backend/cmd/seed.go@@ -7,7 +7,7 @@ import ("github.com/tracewayapp/traceway/backend/app/config""github.com/tracewayapp/traceway/backend/app/db""github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional""github.com/tracewayapp/traceway/backend/app/services""github.com/google/uuid"@@ -20,7 +20,7 @@ func seed(opts *options) error {}_, err := db.ExecuteTransaction(func(tx *sql.Tx) (struct{}, error) {- existing, err := repositories.UserRepository.FindByEmail(tx, opts.defaultUser.email)+ existing, err := transactional.UserRepository.FindByEmail(tx, opts.defaultUser.email)if err != nil {return struct{}{}, err}@@ -34,17 +34,17 @@ func seed(opts *options) error {return struct{}{}, err}- user, err := repositories.UserRepository.Create(tx, opts.defaultUser.email, "Admin", hash)+ user, err := transactional.UserRepository.Create(tx, opts.defaultUser.email, "Admin", hash)if err != nil {return struct{}{}, err}- org, err := repositories.OrganizationRepository.Create(tx, "Default", "UTC")+ org, err := transactional.OrganizationRepository.Create(tx, "Default", "UTC")if err != nil {return struct{}{}, err}- _, err = repositories.OrganizationRepository.AddUser(tx, org.Id, user.Id, "owner")+ _, err = transactional.OrganizationRepository.AddUser(tx, org.Id, user.Id, "owner")if err != nil {return struct{}{}, err}diff --git a/backend/go.mod b/backend/go.modindex 00224719..37e929ee 100644--- a/backend/go.mod+++ b/backend/go.mod@@ -10,6 +10,7 @@ require (github.com/aws/aws-sdk-go-v2/service/s3 v1.96.0github.com/coreos/go-systemd/v22 v22.6.0github.com/dop251/goja v0.0.0-20260607120635-348e6bea910d+ github.com/duckdb/duckdb-go/v2 v2.10504.0github.com/golang-jwt/jwt/v5 v5.3.1github.com/google/pprof v0.0.0-20260604005048-7023385849c0github.com/gorilla/securecookie v1.1.2@@ -32,7 +33,7 @@ require (go.tracewayapp.com v1.0.2go.tracewayapp.com/tracewaygin v1.0.2go.uber.org/zap v1.28.0- modernc.org/sqlite v1.18.1+ modernc.org/sqlite v1.29.6)require (@@ -46,8 +47,16 @@ require (github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.31.0 // indirectgithub.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.53.0 // indirectgithub.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.53.0 // indirect+ github.com/apache/arrow-go/v18 v18.5.1 // indirectgithub.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2 // indirectgithub.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect+ github.com/duckdb/duckdb-go-bindings v0.10504.0 // indirect+ github.com/duckdb/duckdb-go-bindings/lib/darwin-amd64 v0.10504.0 // indirect+ github.com/duckdb/duckdb-go-bindings/lib/darwin-arm64 v0.10504.0 // indirect+ github.com/duckdb/duckdb-go-bindings/lib/linux-amd64 v0.10504.0 // indirect+ github.com/duckdb/duckdb-go-bindings/lib/linux-arm64 v0.10504.0 // indirect+ github.com/duckdb/duckdb-go-bindings/lib/windows-amd64 v0.10504.0 // indirect+ github.com/dustin/go-humanize v1.0.1 // indirectgithub.com/envoyproxy/go-control-plane/envoy v1.37.0 // indirectgithub.com/envoyproxy/protoc-gen-validate v1.3.3 // indirectgithub.com/felixge/httpsnoop v1.0.4 // indirect@@ -56,6 +65,8 @@ require (github.com/go-logr/logr v1.4.3 // indirectgithub.com/go-logr/stdr v1.2.2 // indirectgithub.com/go-sourcemap/sourcemap v2.1.3+incompatible // indirect+ github.com/go-viper/mapstructure/v2 v2.5.0 // indirect+ github.com/google/flatbuffers v25.12.19+incompatible // indirectgithub.com/google/jsonschema-go v0.4.3 // indirectgithub.com/google/s2a-go v0.1.9 // indirectgithub.com/googleapis/enterprise-certificate-proxy v0.3.6 // indirect@@ -63,14 +74,16 @@ require (github.com/gorilla/mux v1.7.4 // indirectgithub.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 // indirectgithub.com/hashicorp/go-version v1.9.0 // indirect- github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect+ github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect+ github.com/ncruces/go-strftime v0.1.9 // indirectgithub.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 // indirectgithub.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect- github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0 // indirect+ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirectgithub.com/segmentio/encoding v0.5.4 // indirectgithub.com/spiffe/go-spiffe/v2 v2.6.0 // indirectgithub.com/stretchr/testify v1.11.1 // indirectgithub.com/yosida95/uritemplate/v3 v3.0.2 // indirect+ github.com/zeebo/xxh3 v1.1.0 // indirectgo.opentelemetry.io/auto/sdk v1.2.1 // indirectgo.opentelemetry.io/collector/component/componentstatus v0.154.0 // indirectgo.opentelemetry.io/collector/consumer/xconsumer v0.154.0 // indirect@@ -87,23 +100,23 @@ require (go.opentelemetry.io/otel/sdk v1.44.0 // indirectgo.opentelemetry.io/otel/sdk/metric v1.44.0 // indirectgo.uber.org/multierr v1.11.0 // indirect+ golang.org/x/exp v0.0.0-20260112195511-716be5621a96 // indirectgolang.org/x/oauth2 v0.36.0 // indirect+ golang.org/x/telemetry v0.0.0-20260409153401-be6f6cb8b1fa // indirectgolang.org/x/time v0.12.0 // indirect+ golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da // indirectgoogle.golang.org/api v0.247.0 // indirectgoogle.golang.org/genproto v0.0.0-20250603155806-513f23925822 // indirectgoogle.golang.org/genproto/googleapis/api v0.0.0-20260226221140-a57be14db171 // indirectgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171 // indirectgoogle.golang.org/grpc v1.81.1 // indirectgopkg.in/yaml.v3 v3.0.1 // indirect- lukechampine.com/uint128 v1.2.0 // indirect- modernc.org/cc/v3 v3.36.3 // indirect- modernc.org/ccgo/v3 v3.16.9 // indirect- modernc.org/libc v1.17.1 // indirect- modernc.org/mathutil v1.5.0 // indirect- modernc.org/memory v1.2.1 // indirect- modernc.org/opt v0.1.3 // indirect- modernc.org/strutil v1.1.3 // indirect- modernc.org/token v1.0.0 // indirect+ modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 // indirect+ modernc.org/libc v1.41.0 // indirect+ modernc.org/mathutil v1.6.0 // indirect+ modernc.org/memory v1.7.2 // indirect+ modernc.org/strutil v1.2.0 // indirect+ modernc.org/token v1.1.0 // indirect)require (@@ -135,10 +148,10 @@ require (github.com/go-playground/locales v0.14.1 // indirectgithub.com/go-playground/universal-translator v0.18.1 // indirectgithub.com/go-playground/validator/v10 v10.27.0 // indirect- github.com/goccy/go-json v0.10.2 // indirect+ github.com/goccy/go-json v0.10.5 // indirectgithub.com/goccy/go-yaml v1.19.2 // indirectgithub.com/json-iterator/go v1.1.12 // indirect- github.com/klauspost/compress v1.18.0 // indirect+ github.com/klauspost/compress v1.18.3 // indirectgithub.com/klauspost/cpuid/v2 v2.3.0 // indirectgithub.com/leodido/go-urn v1.4.0 // indirectgithub.com/mattn/go-isatty v0.0.20 // indirect@@ -146,7 +159,7 @@ require (github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirectgithub.com/paulmach/orb v0.12.0 // indirectgithub.com/pelletier/go-toml/v2 v2.2.4 // indirect- github.com/pierrec/lz4/v4 v4.1.22 // indirect+ github.com/pierrec/lz4/v4 v4.1.25 // indirectgithub.com/quic-go/qpack v0.5.1 // indirectgithub.com/quic-go/quic-go v0.54.0 // indirectgithub.com/segmentio/asm v1.2.1 // indirectdiff --git a/backend/go.sum b/backend/go.sumindex 5c9c83f9..2c773bde 100644--- a/backend/go.sum+++ b/backend/go.sum@@ -42,6 +42,10 @@ github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERogithub.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=github.com/andybalholm/brotli v1.2.0 h1:ukwgCxwYrmACq68yiUqwIWnGY0cTPox/M94sVwToPjQ=github.com/andybalholm/brotli v1.2.0/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=+github.com/apache/arrow-go/v18 v18.5.1 h1:yaQ6zxMGgf9YCYw4/oaeOU3AULySDlAYDOcnr4LdHdI=+github.com/apache/arrow-go/v18 v18.5.1/go.mod h1:OCCJsmdq8AsRm8FkBSSmYTwL/s4zHW9CqxeBxEytkNE=+github.com/apache/thrift v0.22.0 h1:r7mTJdj51TMDe6RtcmNdQxgn9XcyfGDOzegMDRg47uc=+github.com/apache/thrift v0.22.0/go.mod h1:1e7J/O1Ae6ZQMTYdy9xa3w9k+XHWPfRvdPyJeynQ+/g=github.com/aws/aws-sdk-go-v2 v1.41.1 h1:ABlyEARCDLN034NhxlRUSZr4l71mh+T5KAeGh6cerhU=github.com/aws/aws-sdk-go-v2 v1.41.1/go.mod h1:MayyLB8y+buD9hZqkCW3kX1AKq07Y5pXxtgB+rRFhz0=github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.4 h1:489krEF9xIGkOaaX3CE/Be2uWjiXrkCH6gUX+bZA/BU=@@ -114,7 +118,20 @@ github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=github.com/dop251/goja v0.0.0-20260607120635-348e6bea910d h1:xbM5U2EvWKkHxzEQJ2DEn20FwolWZahuTnVHr6WL3Q4=github.com/dop251/goja v0.0.0-20260607120635-348e6bea910d/go.mod h1:Sc+QOu1WruvaaeT/cxFez/pXHpI9ZDjg/E8QNfSVveI=-github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=+github.com/duckdb/duckdb-go-bindings v0.10504.0 h1:XKOXNRetaJnMvMIDqi6etZOmh/nlEHM7saaC5UxU17I=+github.com/duckdb/duckdb-go-bindings v0.10504.0/go.mod h1:M2eB9+zGq+O4opimtLL5nWwkp8vdJQJNbFW5HKdqe4U=+github.com/duckdb/duckdb-go-bindings/lib/darwin-amd64 v0.10504.0 h1:hnWJ9SociR98hpypZPcgB+hTuWgw0hYsYnPFr8mBBEw=+github.com/duckdb/duckdb-go-bindings/lib/darwin-amd64 v0.10504.0/go.mod h1:EnAvZh1kNJHp5yF+M1ZHNEvapnmt6anq1xXHVrAGqMo=+github.com/duckdb/duckdb-go-bindings/lib/darwin-arm64 v0.10504.0 h1:q3JEdS5hU8ytvmcsgFEfGGQeJ5mS8l8QFYpfUlPHDRY=+github.com/duckdb/duckdb-go-bindings/lib/darwin-arm64 v0.10504.0/go.mod h1:IGLSeEcFhNeZF16aVjQCULD7TsFZKG5G7SyKJAXKp5c=+github.com/duckdb/duckdb-go-bindings/lib/linux-amd64 v0.10504.0 h1:2gABzYp2KnclSpE4qqinTZYhGpWSxmNHQKjs9WZ7zWk=+github.com/duckdb/duckdb-go-bindings/lib/linux-amd64 v0.10504.0/go.mod h1:KAIynZ0GHCS7X5fRyuFnQMg/SZBPK/bS9OCOVojClxw=+github.com/duckdb/duckdb-go-bindings/lib/linux-arm64 v0.10504.0 h1:iTFkIVt6Ohd/rTvNQomtbP/IIh90TFGSlOUqFEC68Xo=+github.com/duckdb/duckdb-go-bindings/lib/linux-arm64 v0.10504.0/go.mod h1:81SGOYoEUs8qaAfSk1wRfM5oobrIJ5KI7AzYhK6/bvQ=+github.com/duckdb/duckdb-go-bindings/lib/windows-amd64 v0.10504.0 h1:8O774uudYeexLa+uHekujkT3t3sDjQ7LSnlKIhRNWyc=+github.com/duckdb/duckdb-go-bindings/lib/windows-amd64 v0.10504.0/go.mod h1:K25pJL26ARblGDeuAkrdblFvUen92+CwksLtPEHRqqQ=+github.com/duckdb/duckdb-go/v2 v2.10504.0 h1:bnkcNQpz3EaJmMmfOhFRFJ3ELVDHW4u3PDhZ78ZTCMY=+github.com/duckdb/duckdb-go/v2 v2.10504.0/go.mod h1:DQ8TxrUb0RGyTTFTwPNlpQ9FFx+ocJjoZGDkuOktYp8=github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=github.com/envoyproxy/go-control-plane v0.14.0 h1:hbG2kr4RuFj222B6+7T83thSPqLjwBIfQawTkC++2HA=@@ -156,8 +173,10 @@ github.com/go-playground/validator/v10 v10.27.0 h1:w8+XrWVMhGkxOaaowyKH35gFydVHOgithub.com/go-playground/validator/v10 v10.27.0/go.mod h1:I5QpIEbmr8On7W0TktmJAumgzX4CA1XNl4ZmDuVHKKo=github.com/go-sourcemap/sourcemap v2.1.3+incompatible h1:W1iEw64niKVGogNgBN3ePyLFfuisuzeidWPMPWmECqU=github.com/go-sourcemap/sourcemap v2.1.3+incompatible/go.mod h1:F8jJfvm2KbVjc5NqelyYJmf/v5J0dwNLS2mL4sNA1Jg=-github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=-github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=+github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=+github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=+github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=+github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM=github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=@@ -169,8 +188,11 @@ github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSgithub.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=+github.com/golang/snappy v1.0.0 h1:Oy607GVXHs7RtbggtPBnr2RmDArIsAefDwvrdWvRhGs=+github.com/golang/snappy v1.0.0/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=+github.com/google/flatbuffers v25.12.19+incompatible h1:haMV2JRRJCe1998HeW/p0X9UaMTK6SDo0ffLn2+DbLs=+github.com/google/flatbuffers v25.12.19+incompatible/go.mod h1:1AeVuKshWv4vARoZatz6mlQ0JxURH0Kv5+zNeJKJCa8=github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=-github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=@@ -185,7 +207,6 @@ github.com/google/pprof v0.0.0-20260604005048-7023385849c0 h1:h1QTMDl6q9wDvDCJVpgithub.com/google/pprof v0.0.0-20260604005048-7023385849c0/go.mod h1:MxpfABSjhmINe3F1It9d+8exIHFvUqtLIRCdOGNXqiI=github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0=github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM=-github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=github.com/googleapis/enterprise-certificate-proxy v0.3.6 h1:GW/XbdyBFQ8Qe+YAmFU9uHLo7OnF5tL52HFAgMmyrf4=@@ -202,17 +223,19 @@ github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 h1:HWRh5R2+9EifMyIHV7ZV+MIZqgzgithub.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0/go.mod h1:JfhWUomR1baixubs02l85lZYYOm7LV6om4ceouMv45c=github.com/hashicorp/go-version v1.9.0 h1:CeOIz6k+LoN3qX9Z0tyQrPtiB1DFYRPfCIBtaXPSCnA=github.com/hashicorp/go-version v1.9.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=+github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=+github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=-github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 h1:Z9n2FFNUXsshfwJMBgNA0RU6/i7WVaAegv3PtuIHPMs=-github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:CzGEWj7cYgsdH8dAjBGEr58BoE7ScuLd+fwFZ44+/x8=github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=+github.com/klauspost/asmfmt v1.3.2 h1:4Ri7ox3EwapiOjCki+hw14RyKk201CN4rzyCJRFLpK4=+github.com/klauspost/asmfmt v1.3.2/go.mod h1:AG8TuvYojzulgDAMCnYn50l/5QV3Bs/tp6j0HLHbNSE=github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk=-github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=-github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=+github.com/klauspost/compress v1.18.3 h1:9PJRvfbmTabkOX8moIpXPbMMbYN60bWImDDU7L+/6zw=+github.com/klauspost/compress v1.18.3/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4=github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=@@ -228,12 +251,14 @@ github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=github.com/markbates/goth v1.82.0 h1:8j/c34AjBSTNzO7zTsOyP5IYCQCMBTRBHAbBt/PI0bQ=github.com/markbates/goth v1.82.0/go.mod h1:/DRlcq0pyqkKToyZjsL2KgiA1zbF1HIjE7u2uC79rUk=-github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=-github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=+github.com/minio/asm2plan9s v0.0.0-20200509001527-cdd76441f9d8 h1:AMFGa4R4MiIpspGNG7Z948v4n35fFGB3RR3G/ry4FWs=+github.com/minio/asm2plan9s v0.0.0-20200509001527-cdd76441f9d8/go.mod h1:mC1jAcsrzbxHt8iiaC+zU4b1ylILSosueou12R++wfY=+github.com/minio/c2goasm v0.0.0-20190812172519-36a3d3bbc4f3 h1:+n/aFZefKZp7spd8DFdX7uMikMLXX4oubIzJF4kv/wI=+github.com/minio/c2goasm v0.0.0-20190812172519-36a3d3bbc4f3/go.mod h1:RagcQ7I8IeTMnF8JTXieKnO4Z6JCsikNEzj0DwauVzE=github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0=github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo=github.com/moby/term v0.5.0 h1:xt8Q1nalod/v7BqbG21f8mQPqH+xAaC9C3N3wfWbVP0=@@ -249,6 +274,8 @@ github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWugithub.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc=github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A=github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc=+github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=+github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040=@@ -258,8 +285,8 @@ github.com/paulmach/orb v0.12.0/go.mod h1:5mULz1xQfs3bmQm63QEJA6lNGujuRafwA5S/Engithub.com/paulmach/protoscan v0.2.1/go.mod h1:SpcSwydNLrxUGSDvXvO0P7g7AuhJ7lcKfDlhJCDw2gY=github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=-github.com/pierrec/lz4/v4 v4.1.22 h1:cKFw6uJDK+/gfw5BcDL0JL5aBsAFdsIT18eRtLj7VIU=-github.com/pierrec/lz4/v4 v4.1.22/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4=+github.com/pierrec/lz4/v4 v4.1.25 h1:kocOqRffaIbU5djlIBr7Wh+cx82C0vtFb0fOurZHqD0=+github.com/pierrec/lz4/v4 v4.1.25/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4=github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 h1:GFCKgmp0tecUJ0sJuv4pzYCqS9+RGSn52M3FUwPs+uo=@@ -271,8 +298,8 @@ github.com/quic-go/qpack v0.5.1 h1:giqksBPnT/HDtZ6VhtFKgoLOWmlyo9Ei6u9PqzIMbhI=github.com/quic-go/qpack v0.5.1/go.mod h1:+PC4XFrEskIVkcLzpEkbLqq1uCoxPhQuvK5rH1ZgaEg=github.com/quic-go/quic-go v0.54.0 h1:6s1YB9QotYI6Ospeiguknbp2Znb/jZYjZLRXn9kMQBg=github.com/quic-go/quic-go v0.54.0/go.mod h1:e68ZEaCdyviluZmy44P6Iey98v/Wfz6HCjQEm+l8zTY=-github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0 h1:OdAsTTz6OkFY5QxjkYwrChwuRruF69c169dPK26NUlk=-github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=+github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=+github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=github.com/segmentio/asm v1.2.1 h1:DTNbBqs57ioxAD4PrArqftgypG4/qNpXoJx8TVXxPR0=@@ -310,6 +337,10 @@ github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT0github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d/go.mod h1:rHwXgn7JulP+udvsHwJoVG1YGAP6VLg4y9I5dyZdqmA=github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=+github.com/zeebo/assert v1.3.0 h1:g7C04CbJuIDKNPFHmsk4hwZDO5O+kntRxzaUoNXj+IQ=+github.com/zeebo/assert v1.3.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0=+github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=+github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=go.mongodb.org/mongo-driver v1.11.4/go.mod h1:PTSz5yu21bkT/wXpkS7WR5f0ddqw5quethTUn9WM+2g=go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=@@ -401,6 +432,8 @@ golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhgolang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=golang.org/x/crypto v0.51.0 h1:IBPXwPfKxY7cWQZ38ZCIRPI50YLeevDLlLnyC5wRGTI=golang.org/x/crypto v0.51.0/go.mod h1:8AdwkbraGNABw2kOX6YFPs3WM22XqI4EXEd8g+x7Oc8=+golang.org/x/exp v0.0.0-20260112195511-716be5621a96 h1:Z/6YuSHTLOHfNFdb8zVZomZr7cqNgTJvA8+Qz75D8gU=+golang.org/x/exp v0.0.0-20260112195511-716be5621a96/go.mod h1:nzimsREAkjBCIEFtHiYkrJyT+2uy9YZJB7H1k68CXZU=golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=golang.org/x/mod v0.35.0 h1:Ww1D637e6Pg+Zb2KrWfHQUnH2dQRLBQyAtpr/haaJeM=@@ -422,16 +455,15 @@ golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=-golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=-golang.org/x/sys v0.0.0-20211007075335-d3039528d8ac/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=-golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY=golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=+golang.org/x/telemetry v0.0.0-20260409153401-be6f6cb8b1fa h1:efT73AJZfAAUV7SOip6pWGkwJDzIGiKBZGVzHYa+ve4=+golang.org/x/telemetry v0.0.0-20260409153401-be6f6cb8b1fa/go.mod h1:kHjTxDEnAu6/Nl9lDkzjWpR+bmKfxeiRuSDlsMb70gE=golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=@@ -444,7 +476,6 @@ golang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=-golang.org/x/tools v0.0.0-20201124115921-2c860bdd6e78/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=golang.org/x/tools v0.44.0 h1:UP4ajHPIcuMjT1GqzDWRlalUEoY+uzoZKnhOjbIPD2c=golang.org/x/tools v0.44.0/go.mod h1:KA0AfVErSdxRZIsOVipbv3rQhVXTnlU6UhKxHd1seDI=@@ -452,6 +483,8 @@ golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8Tgolang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=+golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da h1:noIWHXmPHxILtqtCOPIhSt0ABwskkZKjD3bXGnZGpNY=+golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da/go.mod h1:NDW/Ps6MPRej6fsCIbMTohpP40sJ/P/vI1MoTEGwX90=gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=google.golang.org/api v0.247.0 h1:tSd/e0QrUlLsrwMKmkbQhYVa109qIintOls2Wh6bngc=@@ -475,39 +508,19 @@ gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVgopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=-lukechampine.com/uint128 v1.1.1/go.mod h1:c4eWIwlEGaxC/+H1VguhU4PHXNWDCDMUlWdIWl2j1gk=-lukechampine.com/uint128 v1.2.0 h1:mBi/5l91vocEN8otkC5bDLhi2KdCticRiwbdB0O+rjI=-lukechampine.com/uint128 v1.2.0/go.mod h1:c4eWIwlEGaxC/+H1VguhU4PHXNWDCDMUlWdIWl2j1gk=-modernc.org/cc/v3 v3.36.2/go.mod h1:NFUHyPn4ekoC/JHeZFfZurN6ixxawE1BnVonP/oahEI=-modernc.org/cc/v3 v3.36.3 h1:uISP3F66UlixxWEcKuIWERa4TwrZENHSL8tWxZz8bHg=-modernc.org/cc/v3 v3.36.3/go.mod h1:NFUHyPn4ekoC/JHeZFfZurN6ixxawE1BnVonP/oahEI=-modernc.org/ccgo/v3 v3.16.9 h1:AXquSwg7GuMk11pIdw7fmO1Y/ybgazVkMhsZWCV0mHM=-modernc.org/ccgo/v3 v3.16.9/go.mod h1:zNMzC9A9xeNUepy6KuZBbugn3c0Mc9TeiJO4lgvkJDo=-modernc.org/ccorpus v1.11.6 h1:J16RXiiqiCgua6+ZvQot4yUuUy8zxgqbqEEUuGPlISk=-modernc.org/ccorpus v1.11.6/go.mod h1:2gEUTrWqdpH2pXsmTM1ZkjeSrUWDpjMu2T6m29L/ErQ=-modernc.org/httpfs v1.0.6 h1:AAgIpFZRXuYnkjftxTAZwMIiwEqAfk8aVB2/oA6nAeM=-modernc.org/httpfs v1.0.6/go.mod h1:7dosgurJGp0sPaRanU53W4xZYKh14wfzX420oZADeHM=-modernc.org/libc v1.17.0/go.mod h1:XsgLldpP4aWlPlsjqKRdHPqCxCjISdHfM/yeWC5GyW0=-modernc.org/libc v1.17.1 h1:Q8/Cpi36V/QBfuQaFVeisEBs3WqoGAJprZzmf7TfEYI=-modernc.org/libc v1.17.1/go.mod h1:FZ23b+8LjxZs7XtFMbSzL/EhPxNbfZbErxEHc7cbD9s=-modernc.org/mathutil v1.2.2/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E=-modernc.org/mathutil v1.4.1/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E=-modernc.org/mathutil v1.5.0 h1:rV0Ko/6SfM+8G+yKiyI830l3Wuz1zRutdslNoQ0kfiQ=-modernc.org/mathutil v1.5.0/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E=-modernc.org/memory v1.2.0/go.mod h1:/0wo5ibyrQiaoUoH7f9D8dnglAmILJ5/cxZlRECf+Nw=-modernc.org/memory v1.2.1 h1:dkRh86wgmq/bJu2cAS2oqBCz/KsMZU7TUM4CibQ7eBs=-modernc.org/memory v1.2.1/go.mod h1:PkUhL0Mugw21sHPeskwZW4D6VscE/GQJOnIpCnW6pSU=-modernc.org/opt v0.1.1/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0=-modernc.org/opt v0.1.3 h1:3XOZf2yznlhC+ibLltsDGzABUGVx8J6pnFMS3E4dcq4=-modernc.org/opt v0.1.3/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0=-modernc.org/sqlite v1.18.1 h1:ko32eKt3jf7eqIkCgPAeHMBXw3riNSLhl2f3loEF7o8=-modernc.org/sqlite v1.18.1/go.mod h1:6ho+Gow7oX5V+OiOQ6Tr4xeqbx13UZ6t+Fw9IRUG4d4=-modernc.org/strutil v1.1.1/go.mod h1:DE+MQQ/hjKBZS2zNInV5hhcipt5rLPWkmpbGeW5mmdw=-modernc.org/strutil v1.1.3 h1:fNMm+oJklMGYfU9Ylcywl0CO5O6nTfaowNsh2wpPjzY=-modernc.org/strutil v1.1.3/go.mod h1:MEHNA7PdEnEwLvspRMtWTNnp2nnyvMfkimT1NKNAGbw=-modernc.org/tcl v1.13.1 h1:npxzTwFTZYM8ghWicVIX1cRWzj7Nd8i6AqqX2p+IYao=-modernc.org/tcl v1.13.1/go.mod h1:XOLfOwzhkljL4itZkK6T72ckMgvj0BDsnKNdZVUOecw=-modernc.org/token v1.0.0 h1:a0jaWiNMDhDUtqOj09wvjWWAqd3q7WpBulmL9H2egsk=-modernc.org/token v1.0.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=-modernc.org/z v1.5.1 h1:RTNHdsrOpeoSeOF4FbzTo8gBYByaJ5xT7NgZ9ZqRiJM=-modernc.org/z v1.5.1/go.mod h1:eWFB510QWW5Th9YGZT81s+LwvaAs3Q2yr4sP0rmLkv8=+modernc.org/fileutil v1.3.0 h1:gQ5SIzK3H9kdfai/5x41oQiKValumqNTDXMvKo62HvE=+modernc.org/fileutil v1.3.0/go.mod h1:XatxS8fZi3pS8/hKG2GH/ArUogfxjpEKs3Ku3aK4JyQ=+modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 h1:5D53IMaUuA5InSeMu9eJtlQXS2NxAhyWQvkKEgXZhHI=+modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6/go.mod h1:Qz0X07sNOR1jWYCrJMEnbW/X55x206Q7Vt4mz6/wHp4=+modernc.org/libc v1.41.0 h1:g9YAc6BkKlgORsUWj+JwqoB1wU3o4DE3bM3yvA3k+Gk=+modernc.org/libc v1.41.0/go.mod h1:w0eszPsiXoOnoMJgrXjglgLuDy/bt5RR4y3QzUUeodY=+modernc.org/mathutil v1.6.0 h1:fRe9+AmYlaej+64JsEEhoWuAYBkOtQiMEU7n/XgfYi4=+modernc.org/mathutil v1.6.0/go.mod h1:Ui5Q9q1TR2gFm0AQRqQUaBWFLAhQpCwNcuhBOSedWPo=+modernc.org/memory v1.7.2 h1:Klh90S215mmH8c9gO98QxQFsY+W451E8AnzjoE2ee1E=+modernc.org/memory v1.7.2/go.mod h1:NO4NVCQy0N7ln+T9ngWqOQfi7ley4vpwvARR+Hjw95E=+modernc.org/sqlite v1.29.6 h1:0lOXGrycJPptfHDuohfYgNqoe4hu+gYuN/pKgY5XjS4=+modernc.org/sqlite v1.29.6/go.mod h1:S02dvcmm7TnTRvGhv8IGYyLnIt7AS2KPaB1F/71p75U=+modernc.org/strutil v1.2.0 h1:agBi9dp1I+eOnxXeiZawM8F4LawKv4NzGWSaLfyeNZA=+modernc.org/strutil v1.2.0/go.mod h1:/mdcBmfOibveCTBxUl5B5l6W+TTH1FXPLHZE6bTosX0=+modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=+modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=diff --git a/benchmarks/README.md b/benchmarks/README.mdindex bd8e4c83..f01fde8f 100644--- a/benchmarks/README.md+++ b/benchmarks/README.md@@ -154,9 +154,20 @@ Per matrix entry (one tier × one mode × one signal):Measures the SUT under "thousands of small batches/sec from a realSDK fleet" load, which stresses the HTTP/auth/decode/queue path morethan the raw insert path Phase 2 measures.-6. A step "fails" when **either**:+6. A step "fails" when **any** of:- combined error rate (HTTP failures + OTLP `PartialSuccess` rejected items)exceeds `--ingest-err-threshold` (default 5%), **or**+ - the SUT silently dropped rows mid-step: the loadgen polls+ `/api/health/deep` before and after each step and any positive+ `droppedRowsTotal` delta fails the step, since throughput built on+ acked-but-discarded items is not real ingested throughput (DuckDB drops+ rows its appender rejects instead of erroring the request; SQLite and+ ClickHouse report 0 here). The end-of-step snapshot lands in the step+ JSON as `sutIngest`, including DuckDB db/WAL file sizes and engine+ memory, so a latency cliff can be correlated with WAL growth or memory+ pressure after the fact. Read-probe fills record the same counter as+ `droppedRows` per fill level (the true table size is `rowsIngested`+ minus `droppedRows`), **or**- the *achieved* request rate falls below `--soft-cliff-ratio` × target rate(default 70%) — meaning the workers can't keep up with the limiter, theSUT has cliffed on latency, and we'd be erroring out one step later anyway.diff --git a/benchmarks/compose/docker-compose.duckdb.yml b/benchmarks/compose/docker-compose.duckdb.ymlnew file mode 100644index 00000000..8ebea08e--- /dev/null+++ b/benchmarks/compose/docker-compose.duckdb.yml@@ -0,0 +1,29 @@+services:+ traceway:+ build:+ context: ../..+ dockerfile: Dockerfile.duckdb+ ports:+ - "${BENCH_PORT:-8087}:80"+ environment:+ JWT_SECRET: "bench-jwt-secret-not-for-production-use-only-32chars+"+ SQLITE_RETENTION_DAYS: "0"+ SESSION_RECORDING_RETENTION_DAYS: "0"+ DUCKDB_CHECKPOINT_THRESHOLD: "${DUCKDB_CHECKPOINT_THRESHOLD:-256MB}"+ # Without a cap DuckDB assumes ~80% of host RAM for itself and the Go+ # ingest path OOM-storms the whole box under fat-batch load — observed+ # taking dockerd down with it on ccx13.+ DUCKDB_MEMORY_LIMIT: "${DUCKDB_MEMORY_LIMIT:-4GB}"+ GIN_MODE: "release"+ volumes:+ - traceway-bench-duckdb-data:/data+ restart: on-failure:3+ healthcheck:+ test: ["CMD", "wget", "-qO-", "http://localhost/health"]+ interval: 5s+ timeout: 3s+ start_period: 10s+ retries: 20++volumes:+ traceway-bench-duckdb-data:diff --git a/benchmarks/loadgen/ch_snapshot.go b/benchmarks/loadgen/ch_snapshot.goindex 74084f2e..7678bf05 100644--- a/benchmarks/loadgen/ch_snapshot.go+++ b/benchmarks/loadgen/ch_snapshot.go@@ -31,6 +31,21 @@ type chSnapshot struct {MemoryTotalBytes int64 `json:"memoryTotalBytes,omitempty"`}+// ingestStatsSnapshot carries the SUT-side write-path counters from+// /health/deep: silently dropped rows, batch insert failures, and on DuckDB+// engine gauges (db/WAL file size, memory, read-pool waits). Reachable=false+// (missing or unparseable response) makes the caller skip drop-delta+// evaluation rather than fail the step. Older SUT images without these+// fields decode to zeros, which keeps the drop criterion inert.+type ingestStatsSnapshot struct {+ Reachable bool `json:"reachable"`+ DroppedRowsTotal int64 `json:"droppedRowsTotal"`+ InsertFailures int64 `json:"insertFailures"`+ DBSizeBytes int64 `json:"dbSizeBytes,omitempty"`+ WALSizeBytes int64 `json:"walSizeBytes,omitempty"`+ MemoryUsedBytes int64 `json:"memoryUsedBytes,omitempty"`+}+// healthDeepBody mirrors the backend HealthDeepResponse with its JSON tags. The// backend uses `chReachable`/`chUptimeSec`; we expose those as `reachable`/// `uptimeSec` in our embedded snapshot so the bench JSON stays consistent with@@ -45,17 +60,25 @@ type healthDeepBody struct {ErrorsRecent []chError `json:"errorsRecent"`MemoryUsageBytes int64 `json:"memoryUsageBytes"`MemoryTotalBytes int64 `json:"memoryTotalBytes"`+ DroppedRowsTotal int64 `json:"droppedRowsTotal"`+ InsertFailures int64 `json:"insertFailures"`+ Engine *struct {+ DBSizeBytes int64 `json:"dbSizeBytes"`+ WALSizeBytes int64 `json:"walSizeBytes"`+ MemoryUsedBytes int64 `json:"memoryUsedBytes"`+ } `json:"engine"`}-// fetchCHSnapshot pings the backend's /health/deep endpoint and translates the-// payload into a chSnapshot. On any error (timeout, transport, non-2xx, decode)-// it returns a snapshot with Reachable=false and logs to stderrPrefix() — the-// caller does NOT fail the step on a missing snapshot. A 503 from the backend-// (CH unreachable but backend alive) is still parsed and embedded so the JSON-// captures the chReachable=false signal.-func fetchCHSnapshot(ctx context.Context, cfg config, client *http.Client) chSnapshot {+// fetchDeepHealth pings the backend's /health/deep endpoint and splits the+// payload into the ClickHouse snapshot and the write-path ingest stats. On any+// error (timeout, transport, unexpected status, decode) it returns zero-value+// snapshots with Reachable=false and logs to stderrPrefix() — the caller does+// NOT fail the step on a missing snapshot. A 503 from the backend (CH+// telemetry configured but unreachable) is still parsed and embedded so the+// JSON captures the chReachable=false signal.+func fetchDeepHealth(ctx context.Context, cfg config, client *http.Client) (chSnapshot, ingestStatsSnapshot) {if cfg.jwt == "" {- return chSnapshot{}+ return chSnapshot{}, ingestStatsSnapshot{}}reqCtx, cancel := context.WithTimeout(ctx, 5*time.Second)@@ -63,30 +86,30 @@ func fetchCHSnapshot(ctx context.Context, cfg config, client *http.Client) chSnareq, err := http.NewRequestWithContext(reqCtx, http.MethodGet, cfg.target+"/api/health/deep", nil)if err != nil {- fmt.Fprintf(stderrPrefix(), "fetchCHSnapshot: build request failed: %v\n", err)- return chSnapshot{}+ fmt.Fprintf(stderrPrefix(), "fetchDeepHealth: build request failed: %v\n", err)+ return chSnapshot{}, ingestStatsSnapshot{}}req.Header.Set("Authorization", "Bearer "+cfg.jwt)resp, err := client.Do(req)if err != nil {- fmt.Fprintf(stderrPrefix(), "fetchCHSnapshot: http error: %v\n", err)- return chSnapshot{}+ fmt.Fprintf(stderrPrefix(), "fetchDeepHealth: http error: %v\n", err)+ return chSnapshot{}, ingestStatsSnapshot{}}defer resp.Body.Close()if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusServiceUnavailable {- fmt.Fprintf(stderrPrefix(), "fetchCHSnapshot: unexpected status %d\n", resp.StatusCode)- return chSnapshot{}+ fmt.Fprintf(stderrPrefix(), "fetchDeepHealth: unexpected status %d\n", resp.StatusCode)+ return chSnapshot{}, ingestStatsSnapshot{}}var body healthDeepBodyif err := json.NewDecoder(resp.Body).Decode(&body); err != nil {- fmt.Fprintf(stderrPrefix(), "fetchCHSnapshot: decode failed: %v\n", err)- return chSnapshot{}+ fmt.Fprintf(stderrPrefix(), "fetchDeepHealth: decode failed: %v\n", err)+ return chSnapshot{}, ingestStatsSnapshot{}}- return chSnapshot{+ ch := chSnapshot{Reachable: body.CHReachable,UptimeSec: body.CHUptimeSec,PartsCount: body.PartsCount,@@ -97,4 +120,15 @@ func fetchCHSnapshot(ctx context.Context, cfg config, client *http.Client) chSnaMemoryUsageBytes: body.MemoryUsageBytes,MemoryTotalBytes: body.MemoryTotalBytes,}+ ingest := ingestStatsSnapshot{+ Reachable: true,+ DroppedRowsTotal: body.DroppedRowsTotal,+ InsertFailures: body.InsertFailures,+ }+ if body.Engine != nil {+ ingest.DBSizeBytes = body.Engine.DBSizeBytes+ ingest.WALSizeBytes = body.Engine.WALSizeBytes+ ingest.MemoryUsedBytes = body.Engine.MemoryUsedBytes+ }+ return ch, ingest}diff --git a/benchmarks/loadgen/main.go b/benchmarks/loadgen/main.goindex a8f8d4d6..857f5efd 100644--- a/benchmarks/loadgen/main.go+++ b/benchmarks/loadgen/main.go@@ -176,6 +176,7 @@ func main() {writeCheckpoint := func() {out.EndedAt = time.Now().UTC().Format(time.RFC3339)out.ChRestarted = chRestarted.Load()+ out.SutDied = sutDied.Load()out.computeHeadline()if err := writeReportAtomic(cfg.reportOut, &out); err != nil {fmt.Fprintf(os.Stderr, "checkpoint write failed: %v\n", err)@@ -204,6 +205,9 @@ func main() {// phases — the final writeCheckpoint after the switch captures// whatever data was collected up to this point.if err := waitForSutHealthy(ctx, cfg.target, cfg.sutHealthTimeoutSeconds); err != nil {+ if ctx.Err() == nil {+ sutDied.Store(true)+ }fmt.Fprintf(stderrPrefix(), "SUT unhealthy after Phase 1 cooldown — skipping Phase 2/3: %v\n", err)break}@@ -225,6 +229,9 @@ func main() {waitForMergesIdle(ctx, cfg, httpClient, "phase 2 -> phase 3")}if err := waitForSutHealthy(ctx, cfg.target, cfg.sutHealthTimeoutSeconds); err != nil {+ if ctx.Err() == nil {+ sutDied.Store(true)+ }fmt.Fprintf(stderrPrefix(), "SUT unhealthy after Phase 2 cooldown — skipping Phase 3: %v\n", err)break}@@ -258,6 +265,10 @@ func main() {fmt.Fprintln(os.Stderr, "FAILED: ClickHouse restarted during the run; treating result as invalid")os.Exit(1)}+ // Exit 0 unlike chRestarted: passing steps are still a valid lower bound.+ if sutDied.Load() {+ fmt.Fprintln(os.Stderr, "WARNING: SUT died after a failed step and never recovered; headline is a lower bound (cliff not bisected)")+ }}// waitForSutHealthy polls GET <target>/health until it returns 200 or the@@ -334,7 +345,7 @@ func waitForMergesIdle(ctx context.Context, cfg config, client *http.Client, lab// and there are no merges to wait for. Without this fast-path the loop// would burn the full --max-merge-idle-wait (default 5m) between every// phase doing nothing useful.- if first := fetchCHSnapshot(ctx, cfg, client); !first.Reachable {+ if first, _ := fetchDeepHealth(ctx, cfg, client); !first.Reachable {fmt.Fprintf(stderrPrefix(), "merge-idle [%s]: CH not reachable (sqlite mode or backend down) — skipping wait\n", label)return}@@ -350,7 +361,7 @@ func waitForMergesIdle(ctx context.Context, cfg config, client *http.Client, labif ctx.Err() != nil {return}- snap := fetchCHSnapshot(ctx, cfg, client)+ snap, _ := fetchDeepHealth(ctx, cfg, client)fmt.Fprintf(stderrPrefix(), "merge-idle [%s]: reachable=%t activeMerges=%d partsCount=%d longestMerge=%.1fs\n",label, snap.Reachable, snap.ActiveMerges, snap.PartsCount, snap.LongestMergeSec)diff --git a/benchmarks/loadgen/ramp.go b/benchmarks/loadgen/ramp.goindex 33eab851..6df15c2c 100644--- a/benchmarks/loadgen/ramp.go+++ b/benchmarks/loadgen/ramp.go@@ -15,6 +15,7 @@ import (var (lastCHUptime atomic.Int64chRestarted atomic.Bool+ sutDied atomic.Bool)type stepResult struct {@@ -26,8 +27,14 @@ type stepResult struct {Rejected int64 `json:"rejected"`Ingest latencySnapshot `json:"ingest"`CH chSnapshot `json:"ch"`- Passed bool `json:"passed"`- FailReason string `json:"failReason,omitempty"`+ // SutIngest is the end-of-step write-path snapshot from /health/deep+ // (cumulative counters plus DuckDB engine gauges); DroppedItems is the+ // per-step delta of silently dropped rows, which fails the step when+ // nonzero.+ SutIngest *ingestStatsSnapshot `json:"sutIngest,omitempty"`+ DroppedItems int64 `json:"droppedItems,omitempty"`+ Passed bool `json:"passed"`+ FailReason string `json:"failReason,omitempty"`}type phaseResult struct {@@ -53,6 +60,9 @@ type finalReport struct {MaxSustainableItemsPerSec float64 `json:"maxSustainableItemsPerSec,omitempty"`MaxFillLevelPassed int64 `json:"maxFillLevelPassed,omitempty"`ChRestarted bool `json:"chRestarted,omitempty"`+ // SutDied: passing steps stay valid but the headline is only a lower+ // bound — the cliff was never bisected.+ SutDied bool `json:"sutDied,omitempty"`}func (r *finalReport) computeHeadline() {@@ -189,6 +199,9 @@ func runRateRamp(ctx context.Context, cfg config, ing *ingester, ingest *latency}if !s.Passed {firstFailRate = rate+ if !ensureSutRecovered(ctx, cfg, logPrefix) {+ return res+ }break}}@@ -222,12 +235,31 @@ func runRateRamp(ctx context.Context, cfg config, ing *ingester, ingest *latencyif checkpoint != nil {checkpoint(res)}+ if !s.Passed && !ensureSutRecovered(ctx, cfg, logPrefix) {+ break+ }}}return res}+// ensureSutRecovered gates only failed steps — a crash can hide there, while+// a passing step proves liveness. Without it, one fatal step leaves the rest+// of the bisect firing at a dead server and converging to the last pass+// instead of the real cliff.+func ensureSutRecovered(ctx context.Context, cfg config, logPrefix string) bool {+ if err := waitForSutHealthy(ctx, cfg.target, cfg.sutHealthTimeoutSeconds); err != nil {+ // A canceled ctx is the run deadline, not a verdict on the SUT.+ if ctx.Err() == nil {+ sutDied.Store(true)+ fmt.Fprintf(stderrPrefix(), "%s: SUT did not recover after failed step — ending phase, results are lower bounds: %v\n", logPrefix, err)+ }+ return false+ }+ return true+}+// runOneStep resizes the worker pool for the new rate, holds the step for// stepDuration, drains in-flight HTTP for stepDrainSeconds, then snapshots// latency + item counters. The drain window matters: without it, every step@@ -237,6 +269,8 @@ func runOneStep(ctx context.Context, cfg config, ing *ingester, ingest *latencyTingest.SnapshotAndReset()ing.SnapshotAndResetItems()+ _, ingestStatsBase := fetchDeepHealth(ctx, cfg, client)+ing.Start(ctx)stepCtx, cancel := context.WithTimeout(ctx, cfg.stepDuration)@@ -254,7 +288,19 @@ func runOneStep(ctx context.Context, cfg config, ing *ingester, ingest *latencyTsnap := ingest.SnapshotAndReset()attempted, rejected := ing.SnapshotAndResetItems()- ch := fetchCHSnapshot(ctx, cfg, client)+ ch, ingestStatsEnd := fetchDeepHealth(ctx, cfg, client)++ var droppedItems int64+ if ingestStatsBase.Reachable && ingestStatsEnd.Reachable {+ droppedItems = ingestStatsEnd.DroppedRowsTotal - ingestStatsBase.DroppedRowsTotal+ if droppedItems < 0 {+ droppedItems = 0+ }+ }+ var sutIngest *ingestStatsSnapshot+ if ingestStatsEnd.Reachable {+ sutIngest = &ingestStatsEnd+ }// Restart detection: if ClickHouse's uptime is materially less than what// it was at the previous step's snapshot, the CH process restarted during@@ -286,7 +332,7 @@ func runOneStep(ctx context.Context, cfg config, ing *ingester, ingest *latencyTactualIps = float64(actualItems) / elapsed.Seconds()}- passed, reason := evaluateStep(cfg, snap, attempted, rejected, requestRate, elapsed)+ passed, reason := evaluateStep(cfg, snap, attempted, rejected, requestRate, elapsed, droppedItems)if restartedThisStep {passed = falsereason = fmt.Sprintf("CH restarted mid-step (uptime %ds < previous %ds + step %ds)", ch.UptimeSec, prev, int64(elapsed.Seconds()))@@ -301,19 +347,25 @@ func runOneStep(ctx context.Context, cfg config, ing *ingester, ingest *latencyTRejected: rejected,Ingest: snap,CH: ch,+ SutIngest: sutIngest,+ DroppedItems: droppedItems,Passed: passed,FailReason: reason,}}-// evaluateStep combines three failure criteria:+// evaluateStep combines four failure criteria:// 1. HTTP-level error rate + OTLP partial-success rejections > threshold// (combined item-error budget).-// 2. Soft cliff: achieved request rate is far below target. This catches+// 2. Silent drops: the SUT acked requests but its telemetry write path+// discarded rows mid-step (DuckDB drops rows the appender rejects).+// Throughput from such a step is not real ingested throughput, so any+// drop fails the step.+// 3. Soft cliff: achieved request rate is far below target. This catches// the "workers saturated but SUT not yet erroring" state, where latency// has cliffed to multiple seconds and only error-rate-based detection// would let the ramp keep climbing one more step before noticing.-func evaluateStep(cfg config, snap latencySnapshot, attempted, rejected int64, targetRate float64, elapsed time.Duration) (bool, string) {+func evaluateStep(cfg config, snap latencySnapshot, attempted, rejected int64, targetRate float64, elapsed time.Duration, droppedItems int64) (bool, string) {totalReq := snap.OK + snap.Errorsif totalReq == 0 {return false, "no requests completed"@@ -328,6 +380,9 @@ func evaluateStep(cfg config, snap latencySnapshot, attempted, rejected int64, treturn false, fmt.Sprintf("combined error rate %.2f%% (http %.2f%% + rejected %.2f%%) > %.2f%% threshold",combined*100, httpErrRate*100, rejectRate*100, cfg.ingestErrThreshold*100)}+ if droppedItems > 0 {+ return false, fmt.Sprintf("SUT silently dropped %d rows mid-step (acked but not stored)", droppedItems)+ }if targetRate > 0 && elapsed > 0 && cfg.softCliffRatio > 0 {achievedRate := float64(snap.OK) / elapsed.Seconds()if achievedRate < targetRate*cfg.softCliffRatio {diff --git a/benchmarks/loadgen/read_probe.go b/benchmarks/loadgen/read_probe.goindex 69bcca54..aa2cde4f 100644--- a/benchmarks/loadgen/read_probe.go+++ b/benchmarks/loadgen/read_probe.go@@ -21,11 +21,15 @@ type endpointProbeResult struct {}type readProbeStep struct {- FillLevelTarget int64 `json:"fillLevelTarget"`- RowsIngested int64 `json:"rowsIngested"`- IngestSecondsElapsed float64 `json:"ingestSecondsElapsed"`- Probes []endpointProbeResult `json:"probes"`- MedianLatencyMs float64 `json:"medianLatencyMs"`+ FillLevelTarget int64 `json:"fillLevelTarget"`+ RowsIngested int64 `json:"rowsIngested"`+ IngestSecondsElapsed float64 `json:"ingestSecondsElapsed"`+ // DroppedRows is cumulative since scenario start, mirroring RowsIngested.+ // Nonzero means the SUT silently discarded rows during fill, so the true+ // table size is RowsIngested minus DroppedRows.+ DroppedRows int64 `json:"droppedRows,omitempty"`+ Probes []endpointProbeResult `json:"probes"`+ MedianLatencyMs float64 `json:"medianLatencyMs"`// Back-compat: equals MedianLatencyMs and AND-of-all-probe-Ok respectively.// Existing chart.py renderers (and post-1 readers) consume these.ReadLatencyMs float64 `json:"readLatencyMs"`@@ -86,6 +90,8 @@ func runReadProbe(ctx context.Context, cfg config, ing *ingester, ingestStats *ling.SnapshotAndResetItems()ingestStats.SnapshotAndReset()+ _, sutStatsBase := fetchDeepHealth(ctx, cfg, client)+var totalIngested int64for _, target := range cfg.fillLevels {@@ -108,6 +114,15 @@ func runReadProbe(ctx context.Context, cfg config, ing *ingester, ingestStats *ltotalIngested += extraAttemptedstep.RowsIngested = totalIngested+ if sutStatsBase.Reachable {+ if _, cur := fetchDeepHealth(ctx, cfg, client); cur.Reachable {+ if dropped := cur.DroppedRowsTotal - sutStatsBase.DroppedRowsTotal; dropped > 0 {+ step.DroppedRows = dropped+ fmt.Fprintf(stderrPrefix(), "read-probe: SUT silently dropped %d rows during fill; true table size is below the fill target\n", dropped)+ }+ }+ }+fmt.Fprintf(stderrPrefix(), "read-probe fill=%d rows reached in %.1fs (signal=%s) — settling %ds\n",step.RowsIngested, step.IngestSecondsElapsed, cfg.signal, res.SettleSeconds)diff --git a/benchmarks/scripts/run-matrix-entry.sh b/benchmarks/scripts/run-matrix-entry.shindex faca66c1..bf4013ec 100755--- a/benchmarks/scripts/run-matrix-entry.sh+++ b/benchmarks/scripts/run-matrix-entry.sh@@ -6,7 +6,7 @@## Usage: run-matrix-entry.sh <tier> <mode> <signal> <duration> <out-dir> [smoke] [async]# <tier> ccx13 | ccx23 | ccx33 | ccx43-# <mode> sqlite | pgch+# <mode> sqlite | duckdb | pgch | managed-ch# <signal> spans | metrics | logs# <duration> Loadgen total runtime, e.g. 30m, 3m# <out-dir> Directory to write <tier>-<mode>-<signal>.json into@@ -18,6 +18,7 @@set -euo pipefailSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+source "${SCRIPT_DIR}/_ssh.sh"if [[ $# -lt 5 ]]; thenecho "usage: $0 <tier> <mode> <signal> <duration> <out-dir> [smoke] [async]" >&2@@ -101,14 +102,21 @@ if [[ "${SCENARIO}" == "read-probe" ]]; thenif [[ -n "${BENCH_FILL_REQUEST_RATE:-}" ]]; thenextra_args+=( --fill-request-rate "${BENCH_FILL_REQUEST_RATE}" )fi+ # Custom fill ladder (e.g. 10000000,100000000,1000000000 to probe 1B).+ # Appended after any smoke override, so the explicit request wins.+ if [[ -n "${BENCH_FILL_LEVELS:-}" ]]; then+ extra_args+=( --fill-levels "${BENCH_FILL_LEVELS}" )+ fifi-# SQLite has no merge-idle equivalent — /health/deep returns chReachable=false-# and waitForMergesIdle skips immediately. Compensate with a longer per-step-# drain and a fixed inter-phase cooldown so the SUT can finish digesting-# Phase 1's wake (zombie goroutines + WAL checkpoint) before Phase 2 starts.-# Without this, Phase 1 step-cliff contaminates Phase 2's first step.-if [[ "${MODE}" == "sqlite" && "${SCENARIO}" == "throughput" && "${SMOKE}" != "smoke" ]]; then+# SQLite and DuckDB have no merge-idle equivalent — /health/deep returns+# chReachable=false and waitForMergesIdle skips immediately. Compensate with a+# longer per-step drain and a fixed inter-phase cooldown so the SUT can finish+# digesting Phase 1's wake (zombie goroutines + WAL checkpoint) before Phase 2+# starts. Without this, Phase 1 step-cliff contaminates Phase 2's first step —+# observed on DuckDB as a phase-2 "no requests completed" wipeout while its+# post-phase-1 checkpoint stalled the synchronous ingest path.+if [[ ( "${MODE}" == "sqlite" || "${MODE}" == "duckdb" ) && "${SCENARIO}" == "throughput" && "${SMOKE}" != "smoke" ]]; thenextra_args+=( --step-drain-seconds 60s --inter-phase-cooldown-seconds 60s )fi@@ -124,5 +132,63 @@ OUT_PATH="${OUT_DIR}/${TIER}-${MODE}-${SIGNAL}-${SCENARIO}${async_suffix}.json""${OUT_PATH}" \"${extra_args[@]}"+if [[ ( "${MODE}" == "sqlite" || "${MODE}" == "duckdb" ) && -f "${OUT_PATH}" ]]; then+ if [[ "${SCENARIO}" == "read-probe" ]]; then+ # rowsIngested is cumulative per step, so max = total.+ disk_rows="$(jq '[.readProbe.steps[]?.rowsIngested] | max // 0' "${OUT_PATH}")"+ else+ disk_rows="$(jq '[.phase1.steps[]?, .phase2.steps[]?, .phase3.steps[]? | (.ingest.ok // 0) * (.batchSize // 0)] | add // 0' "${OUT_PATH}")"+ fi+ case "${MODE}" in+ sqlite) disk_glob='/t/*_telemetry.db*' ;;+ duckdb) disk_glob='/t/*_telemetry.duckdb*' ;;+ esac+ echo "measuring ${MODE} telemetry on-disk size (rows ingested per result JSON: ${disk_rows})" >&2+ # busybox du has no -b, so measure in KB and convert.+ disk_remote="vol=\$(docker volume ls --format '{{.Name}}' | grep -E '${MODE}-data' | head -1)+if [ -z \"\$vol\" ]; then echo 'no matching volume' >&2; exit 3; fi+kb=\$(docker run --rm -v \"\$vol\":/t alpine:3.20 sh -c 'du -ck ${disk_glob} 2>/dev/null | tail -1' | awk '{print \$1}')+if [ -z \"\$kb\" ]; then echo 'du produced no output (telemetry file missing?)' >&2; exit 5; fi+echo \$((kb * 1024))"+ disk_bytes="$(bench_ssh "${SUT_PUBLIC_IP}" "${disk_remote}" | tail -1 || true)"+ if [[ "${disk_bytes}" =~ ^[0-9]+$ ]]; then+ [[ "${disk_rows}" =~ ^[0-9]+$ ]] || disk_rows=0+ tmp_disk="$(mktemp)"+ if jq --argjson b "${disk_bytes}" --argjson r "${disk_rows}" \+ '. + {bytesOnDisk: $b, storedRows: $r}' \+ "${OUT_PATH}" > "${tmp_disk}"; then+ mv "${tmp_disk}" "${OUT_PATH}"+ bps="n/a"; [[ "${disk_rows}" -gt 0 ]] && bps="$(awk -v b="${disk_bytes}" -v r="${disk_rows}" 'BEGIN{printf "%.2f", b/r}')"+ echo "disk: ${MODE} telemetry = ${disk_bytes} bytes over ${disk_rows} ingested items (${bps} bytes/item)" >&2+ else+ rm -f "${tmp_disk}"+ echo "disk: jq patch failed (non-fatal)" >&2+ fi+ else+ echo "disk: measurement failed (got '${disk_bytes}', non-fatal)" >&2+ fi+fi++# Post-mortem before teardown deletes the server — after that, an OOM kill and+# a crash loop are indistinguishable.+if [[ -f "${OUT_PATH}" ]]; then+ sut_state_remote="cid=\$(docker ps -aq --filter 'name=traceway' | head -1)+if [ -z \"\$cid\" ]; then echo '{}'; exit 0; fi+docker inspect --format '{\"status\":\"{{.State.Status}}\",\"oomKilled\":{{.State.OOMKilled}},\"exitCode\":{{.State.ExitCode}},\"restartCount\":{{.RestartCount}}}' \"\$cid\""+ sut_state="$(bench_ssh "${SUT_PUBLIC_IP}" "${sut_state_remote}" | tail -1 || echo '{}')"+ if jq -e . >/dev/null 2>&1 <<< "${sut_state}"; then+ tmp_state="$(mktemp)"+ if jq --argjson s "${sut_state}" '. + {sutContainer: $s}' "${OUT_PATH}" > "${tmp_state}"; then+ mv "${tmp_state}" "${OUT_PATH}"+ echo "sut container state: ${sut_state}" >&2+ else+ rm -f "${tmp_state}"+ fi+ else+ echo "sut container state capture failed (non-fatal): ${sut_state}" >&2+ fi+ bench_ssh "${SUT_PUBLIC_IP}" "cid=\$(docker ps -aq --filter 'name=traceway' | head -1); [ -n \"\$cid\" ] && docker logs --tail 30 \"\$cid\" 2>&1 | sed 's/^/sut-log: /'" >&2 || true+fi+# Trap handles teardown — no explicit call needed.echo "matrix entry ${TIER}-${MODE}-${SIGNAL}-${SCENARIO}${async_suffix} complete -> ${OUT_PATH}" >&2diff --git a/benchmarks/scripts/sut-bootstrap.sh b/benchmarks/scripts/sut-bootstrap.shindex c5fa285a..8868ff20 100755--- a/benchmarks/scripts/sut-bootstrap.sh+++ b/benchmarks/scripts/sut-bootstrap.sh@@ -8,7 +8,7 @@# 5. Poll /health until 200.## Usage: sut-bootstrap.sh <sut-public-ip> <mode>-# <mode> sqlite | pgch+# <mode> sqlite | duckdb | pgch | managed-chset -euo pipefailSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"@@ -24,8 +24,8 @@ SUT_IP="$1"MODE="$2"case "${MODE}" in- sqlite|pgch|managed-ch) ;;- *) echo "mode must be sqlite, pgch, or managed-ch, got: ${MODE}" >&2; exit 2 ;;+ sqlite|duckdb|pgch|managed-ch) ;;+ *) echo "mode must be sqlite, duckdb, pgch, or managed-ch, got: ${MODE}" >&2; exit 2 ;;esacif [[ "${MODE}" == "managed-ch" ]]; then@@ -58,6 +58,7 @@ bench_rsync \--exclude 'benchmarks/results' \--exclude 'traceway.db*' \--exclude 'traceway_telemetry.db*' \+ --exclude 'traceway_telemetry.duckdb*' \--exclude 'backend/storage' \"${REPO_ROOT}/" "root@${SUT_IP}:/opt/traceway/"diff --git a/cli/test/contract/go.mod b/cli/test/contract/go.modindex dce69dc0..6cd8ba73 100644--- a/cli/test/contract/go.mod+++ b/cli/test/contract/go.mod@@ -14,6 +14,7 @@ require (github.com/ClickHouse/ch-go v0.69.0 // indirectgithub.com/ClickHouse/clickhouse-go/v2 v2.42.0 // indirectgithub.com/andybalholm/brotli v1.2.0 // indirect+ github.com/apache/arrow-go/v18 v18.5.1 // indirectgithub.com/aws/aws-sdk-go-v2 v1.41.1 // indirectgithub.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.4 // indirectgithub.com/aws/aws-sdk-go-v2/config v1.32.7 // indirect@@ -39,6 +40,14 @@ require (github.com/cloudwego/base64x v0.1.6 // indirectgithub.com/coreos/go-systemd/v22 v22.6.0 // indirectgithub.com/dop251/goja v0.0.0-20260607120635-348e6bea910d // indirect+ github.com/duckdb/duckdb-go-bindings v0.10504.0 // indirect+ github.com/duckdb/duckdb-go-bindings/lib/darwin-amd64 v0.10504.0 // indirect+ github.com/duckdb/duckdb-go-bindings/lib/darwin-arm64 v0.10504.0 // indirect+ github.com/duckdb/duckdb-go-bindings/lib/linux-amd64 v0.10504.0 // indirect+ github.com/duckdb/duckdb-go-bindings/lib/linux-arm64 v0.10504.0 // indirect+ github.com/duckdb/duckdb-go-bindings/lib/windows-amd64 v0.10504.0 // indirect+ github.com/duckdb/duckdb-go/v2 v2.10504.0 // indirect+ github.com/dustin/go-humanize v1.0.1 // indirectgithub.com/gabriel-vasile/mimetype v1.4.8 // indirectgithub.com/gin-contrib/sse v1.1.0 // indirectgithub.com/gin-gonic/gin v1.11.0 // indirect@@ -49,20 +58,22 @@ require (github.com/go-playground/universal-translator v0.18.1 // indirectgithub.com/go-playground/validator/v10 v10.27.0 // indirectgithub.com/go-sourcemap/sourcemap v2.1.3+incompatible // indirect- github.com/goccy/go-json v0.10.2 // indirect+ github.com/go-viper/mapstructure/v2 v2.5.0 // indirect+ github.com/goccy/go-json v0.10.5 // indirectgithub.com/goccy/go-yaml v1.19.2 // indirectgithub.com/golang-jwt/jwt/v5 v5.3.1 // indirectgithub.com/golang-migrate/migrate/v4 v4.19.1 // indirect+ github.com/google/flatbuffers v25.12.19+incompatible // indirectgithub.com/google/jsonschema-go v0.4.3 // indirectgithub.com/google/pprof v0.0.0-20260604005048-7023385849c0 // indirectgithub.com/gorilla/mux v1.7.4 // indirectgithub.com/gorilla/securecookie v1.1.2 // indirectgithub.com/gorilla/sessions v1.4.0 // indirectgithub.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 // indirect+ github.com/hashicorp/golang-lru/v2 v2.0.7 // indirectgithub.com/joho/godotenv v1.5.1 // indirectgithub.com/json-iterator/go v1.1.12 // indirect- github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect- github.com/klauspost/compress v1.18.0 // indirect+ github.com/klauspost/compress v1.18.3 // indirectgithub.com/klauspost/cpuid/v2 v2.3.0 // indirectgithub.com/leodido/go-urn v1.4.0 // indirectgithub.com/lib/pq v1.10.9 // indirect@@ -70,12 +81,13 @@ require (github.com/mattn/go-isatty v0.0.20 // indirectgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirectgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect+ github.com/ncruces/go-strftime v0.1.9 // indirectgithub.com/paulmach/orb v0.12.0 // indirectgithub.com/pelletier/go-toml/v2 v2.2.4 // indirect- github.com/pierrec/lz4/v4 v4.1.22 // indirect+ github.com/pierrec/lz4/v4 v4.1.25 // indirectgithub.com/quic-go/qpack v0.5.1 // indirectgithub.com/quic-go/quic-go v0.54.0 // indirect- github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0 // indirect+ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirectgithub.com/segmentio/asm v1.2.1 // indirectgithub.com/segmentio/encoding v0.5.4 // indirectgithub.com/shopspring/decimal v1.4.0 // indirect@@ -83,6 +95,7 @@ require (github.com/twitchyliquid64/golang-asm v0.15.1 // indirectgithub.com/ugorji/go/codec v1.3.0 // indirectgithub.com/yosida95/uritemplate/v3 v3.0.2 // indirect+ github.com/zeebo/xxh3 v1.1.0 // indirectgo.opentelemetry.io/otel v1.44.0 // indirectgo.opentelemetry.io/otel/trace v1.44.0 // indirectgo.opentelemetry.io/proto/otlp v1.10.0 // indirect@@ -94,27 +107,27 @@ require (go.yaml.in/yaml/v3 v3.0.4 // indirectgolang.org/x/arch v0.20.0 // indirectgolang.org/x/crypto v0.51.0 // indirect+ golang.org/x/exp v0.0.0-20260112195511-716be5621a96 // indirectgolang.org/x/mod v0.35.0 // indirectgolang.org/x/net v0.55.0 // indirectgolang.org/x/oauth2 v0.36.0 // indirectgolang.org/x/sync v0.20.0 // indirectgolang.org/x/sys v0.45.0 // indirect+ golang.org/x/telemetry v0.0.0-20260409153401-be6f6cb8b1fa // indirectgolang.org/x/text v0.37.0 // indirectgolang.org/x/tools v0.44.0 // indirect+ golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da // indirectgoogle.golang.org/genproto/googleapis/api v0.0.0-20260226221140-a57be14db171 // indirectgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171 // indirectgoogle.golang.org/grpc v1.81.1 // indirectgoogle.golang.org/protobuf v1.36.11 // indirect- lukechampine.com/uint128 v1.2.0 // indirect- modernc.org/cc/v3 v3.36.3 // indirect- modernc.org/ccgo/v3 v3.16.9 // indirect- modernc.org/libc v1.17.1 // indirect- modernc.org/mathutil v1.5.0 // indirect- modernc.org/memory v1.2.1 // indirect- modernc.org/opt v0.1.3 // indirect- modernc.org/sqlite v1.18.1 // indirect- modernc.org/strutil v1.1.3 // indirect- modernc.org/token v1.0.0 // indirect+ modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 // indirect+ modernc.org/libc v1.41.0 // indirect+ modernc.org/mathutil v1.6.0 // indirect+ modernc.org/memory v1.7.2 // indirect+ modernc.org/sqlite v1.29.6 // indirect+ modernc.org/strutil v1.2.0 // indirect+ modernc.org/token v1.1.0 // indirect)replace github.com/tracewayapp/traceway/cli => ../..diff --git a/cli/test/contract/go.sum b/cli/test/contract/go.sumindex 4ac91c12..458a8518 100644--- a/cli/test/contract/go.sum+++ b/cli/test/contract/go.sum@@ -14,6 +14,10 @@ github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERogithub.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=github.com/andybalholm/brotli v1.2.0 h1:ukwgCxwYrmACq68yiUqwIWnGY0cTPox/M94sVwToPjQ=github.com/andybalholm/brotli v1.2.0/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=+github.com/apache/arrow-go/v18 v18.5.1 h1:yaQ6zxMGgf9YCYw4/oaeOU3AULySDlAYDOcnr4LdHdI=+github.com/apache/arrow-go/v18 v18.5.1/go.mod h1:OCCJsmdq8AsRm8FkBSSmYTwL/s4zHW9CqxeBxEytkNE=+github.com/apache/thrift v0.22.0 h1:r7mTJdj51TMDe6RtcmNdQxgn9XcyfGDOzegMDRg47uc=+github.com/apache/thrift v0.22.0/go.mod h1:1e7J/O1Ae6ZQMTYdy9xa3w9k+XHWPfRvdPyJeynQ+/g=github.com/aws/aws-sdk-go-v2 v1.41.1 h1:ABlyEARCDLN034NhxlRUSZr4l71mh+T5KAeGh6cerhU=github.com/aws/aws-sdk-go-v2 v1.41.1/go.mod h1:MayyLB8y+buD9hZqkCW3kX1AKq07Y5pXxtgB+rRFhz0=github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.4 h1:489krEF9xIGkOaaX3CE/Be2uWjiXrkCH6gUX+bZA/BU=@@ -84,7 +88,20 @@ github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=github.com/dop251/goja v0.0.0-20260607120635-348e6bea910d h1:xbM5U2EvWKkHxzEQJ2DEn20FwolWZahuTnVHr6WL3Q4=github.com/dop251/goja v0.0.0-20260607120635-348e6bea910d/go.mod h1:Sc+QOu1WruvaaeT/cxFez/pXHpI9ZDjg/E8QNfSVveI=-github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=+github.com/duckdb/duckdb-go-bindings v0.10504.0 h1:XKOXNRetaJnMvMIDqi6etZOmh/nlEHM7saaC5UxU17I=+github.com/duckdb/duckdb-go-bindings v0.10504.0/go.mod h1:M2eB9+zGq+O4opimtLL5nWwkp8vdJQJNbFW5HKdqe4U=+github.com/duckdb/duckdb-go-bindings/lib/darwin-amd64 v0.10504.0 h1:hnWJ9SociR98hpypZPcgB+hTuWgw0hYsYnPFr8mBBEw=+github.com/duckdb/duckdb-go-bindings/lib/darwin-amd64 v0.10504.0/go.mod h1:EnAvZh1kNJHp5yF+M1ZHNEvapnmt6anq1xXHVrAGqMo=+github.com/duckdb/duckdb-go-bindings/lib/darwin-arm64 v0.10504.0 h1:q3JEdS5hU8ytvmcsgFEfGGQeJ5mS8l8QFYpfUlPHDRY=+github.com/duckdb/duckdb-go-bindings/lib/darwin-arm64 v0.10504.0/go.mod h1:IGLSeEcFhNeZF16aVjQCULD7TsFZKG5G7SyKJAXKp5c=+github.com/duckdb/duckdb-go-bindings/lib/linux-amd64 v0.10504.0 h1:2gABzYp2KnclSpE4qqinTZYhGpWSxmNHQKjs9WZ7zWk=+github.com/duckdb/duckdb-go-bindings/lib/linux-amd64 v0.10504.0/go.mod h1:KAIynZ0GHCS7X5fRyuFnQMg/SZBPK/bS9OCOVojClxw=+github.com/duckdb/duckdb-go-bindings/lib/linux-arm64 v0.10504.0 h1:iTFkIVt6Ohd/rTvNQomtbP/IIh90TFGSlOUqFEC68Xo=+github.com/duckdb/duckdb-go-bindings/lib/linux-arm64 v0.10504.0/go.mod h1:81SGOYoEUs8qaAfSk1wRfM5oobrIJ5KI7AzYhK6/bvQ=+github.com/duckdb/duckdb-go-bindings/lib/windows-amd64 v0.10504.0 h1:8O774uudYeexLa+uHekujkT3t3sDjQ7LSnlKIhRNWyc=+github.com/duckdb/duckdb-go-bindings/lib/windows-amd64 v0.10504.0/go.mod h1:K25pJL26ARblGDeuAkrdblFvUen92+CwksLtPEHRqqQ=+github.com/duckdb/duckdb-go/v2 v2.10504.0 h1:bnkcNQpz3EaJmMmfOhFRFJ3ELVDHW4u3PDhZ78ZTCMY=+github.com/duckdb/duckdb-go/v2 v2.10504.0/go.mod h1:DQ8TxrUb0RGyTTFTwPNlpQ9FFx+ocJjoZGDkuOktYp8=github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=@@ -115,8 +132,10 @@ github.com/go-playground/validator/v10 v10.27.0 h1:w8+XrWVMhGkxOaaowyKH35gFydVHOgithub.com/go-playground/validator/v10 v10.27.0/go.mod h1:I5QpIEbmr8On7W0TktmJAumgzX4CA1XNl4ZmDuVHKKo=github.com/go-sourcemap/sourcemap v2.1.3+incompatible h1:W1iEw64niKVGogNgBN3ePyLFfuisuzeidWPMPWmECqU=github.com/go-sourcemap/sourcemap v2.1.3+incompatible/go.mod h1:F8jJfvm2KbVjc5NqelyYJmf/v5J0dwNLS2mL4sNA1Jg=-github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=-github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=+github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=+github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=+github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=+github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM=github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=@@ -128,8 +147,11 @@ github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSgithub.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=+github.com/golang/snappy v1.0.0 h1:Oy607GVXHs7RtbggtPBnr2RmDArIsAefDwvrdWvRhGs=+github.com/golang/snappy v1.0.0/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=+github.com/google/flatbuffers v25.12.19+incompatible h1:haMV2JRRJCe1998HeW/p0X9UaMTK6SDo0ffLn2+DbLs=+github.com/google/flatbuffers v25.12.19+incompatible/go.mod h1:1AeVuKshWv4vARoZatz6mlQ0JxURH0Kv5+zNeJKJCa8=github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=-github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=@@ -140,7 +162,6 @@ github.com/google/jsonschema-go v0.4.3 h1:/DBOLZTfDow7pe2GmaJNhltueGTtDKICi8V8p+github.com/google/jsonschema-go v0.4.3/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=github.com/google/pprof v0.0.0-20260604005048-7023385849c0 h1:h1QTMDl6q9wDvDCJVpKQSjgleGFYnd2fOxmg2K+6BGE=github.com/google/pprof v0.0.0-20260604005048-7023385849c0/go.mod h1:MxpfABSjhmINe3F1It9d+8exIHFvUqtLIRCdOGNXqiI=-github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=github.com/gorilla/mux v1.7.4 h1:VuZ8uybHlWmqV03+zRzdwKL4tUnIp1MAQtp1mIFE1bc=@@ -151,17 +172,19 @@ github.com/gorilla/sessions v1.4.0 h1:kpIYOp/oi6MG/p5PgxApU8srsSw9tuFbt46Lt7auzqgithub.com/gorilla/sessions v1.4.0/go.mod h1:FLWm50oby91+hl7p/wRxDth9bWSuk0qVL2emc7lT5ik=github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 h1:HWRh5R2+9EifMyIHV7ZV+MIZqgz+PMpZ14Jynv3O2Zs=github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0/go.mod h1:JfhWUomR1baixubs02l85lZYYOm7LV6om4ceouMv45c=+github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=+github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=-github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 h1:Z9n2FFNUXsshfwJMBgNA0RU6/i7WVaAegv3PtuIHPMs=-github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:CzGEWj7cYgsdH8dAjBGEr58BoE7ScuLd+fwFZ44+/x8=github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=+github.com/klauspost/asmfmt v1.3.2 h1:4Ri7ox3EwapiOjCki+hw14RyKk201CN4rzyCJRFLpK4=+github.com/klauspost/asmfmt v1.3.2/go.mod h1:AG8TuvYojzulgDAMCnYn50l/5QV3Bs/tp6j0HLHbNSE=github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk=-github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=-github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=+github.com/klauspost/compress v1.18.3 h1:9PJRvfbmTabkOX8moIpXPbMMbYN60bWImDDU7L+/6zw=+github.com/klauspost/compress v1.18.3/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4=github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=@@ -177,12 +200,14 @@ github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=github.com/markbates/goth v1.82.0 h1:8j/c34AjBSTNzO7zTsOyP5IYCQCMBTRBHAbBt/PI0bQ=github.com/markbates/goth v1.82.0/go.mod h1:/DRlcq0pyqkKToyZjsL2KgiA1zbF1HIjE7u2uC79rUk=-github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=-github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=+github.com/minio/asm2plan9s v0.0.0-20200509001527-cdd76441f9d8 h1:AMFGa4R4MiIpspGNG7Z948v4n35fFGB3RR3G/ry4FWs=+github.com/minio/asm2plan9s v0.0.0-20200509001527-cdd76441f9d8/go.mod h1:mC1jAcsrzbxHt8iiaC+zU4b1ylILSosueou12R++wfY=+github.com/minio/c2goasm v0.0.0-20190812172519-36a3d3bbc4f3 h1:+n/aFZefKZp7spd8DFdX7uMikMLXX4oubIzJF4kv/wI=+github.com/minio/c2goasm v0.0.0-20190812172519-36a3d3bbc4f3/go.mod h1:RagcQ7I8IeTMnF8JTXieKnO4Z6JCsikNEzj0DwauVzE=github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0=github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo=github.com/moby/term v0.5.0 h1:xt8Q1nalod/v7BqbG21f8mQPqH+xAaC9C3N3wfWbVP0=@@ -198,6 +223,8 @@ github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWugithub.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc=github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A=github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc=+github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=+github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040=@@ -207,8 +234,8 @@ github.com/paulmach/orb v0.12.0/go.mod h1:5mULz1xQfs3bmQm63QEJA6lNGujuRafwA5S/Engithub.com/paulmach/protoscan v0.2.1/go.mod h1:SpcSwydNLrxUGSDvXvO0P7g7AuhJ7lcKfDlhJCDw2gY=github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=-github.com/pierrec/lz4/v4 v4.1.22 h1:cKFw6uJDK+/gfw5BcDL0JL5aBsAFdsIT18eRtLj7VIU=-github.com/pierrec/lz4/v4 v4.1.22/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4=+github.com/pierrec/lz4/v4 v4.1.25 h1:kocOqRffaIbU5djlIBr7Wh+cx82C0vtFb0fOurZHqD0=+github.com/pierrec/lz4/v4 v4.1.25/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4=github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=@@ -218,8 +245,8 @@ github.com/quic-go/qpack v0.5.1 h1:giqksBPnT/HDtZ6VhtFKgoLOWmlyo9Ei6u9PqzIMbhI=github.com/quic-go/qpack v0.5.1/go.mod h1:+PC4XFrEskIVkcLzpEkbLqq1uCoxPhQuvK5rH1ZgaEg=github.com/quic-go/quic-go v0.54.0 h1:6s1YB9QotYI6Ospeiguknbp2Znb/jZYjZLRXn9kMQBg=github.com/quic-go/quic-go v0.54.0/go.mod h1:e68ZEaCdyviluZmy44P6Iey98v/Wfz6HCjQEm+l8zTY=-github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0 h1:OdAsTTz6OkFY5QxjkYwrChwuRruF69c169dPK26NUlk=-github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=+github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=+github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8=github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4=github.com/segmentio/asm v1.2.1 h1:DTNbBqs57ioxAD4PrArqftgypG4/qNpXoJx8TVXxPR0=@@ -255,6 +282,10 @@ github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT0github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d/go.mod h1:rHwXgn7JulP+udvsHwJoVG1YGAP6VLg4y9I5dyZdqmA=github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=+github.com/zeebo/assert v1.3.0 h1:g7C04CbJuIDKNPFHmsk4hwZDO5O+kntRxzaUoNXj+IQ=+github.com/zeebo/assert v1.3.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0=+github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=+github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=go.mongodb.org/mongo-driver v1.11.4/go.mod h1:PTSz5yu21bkT/wXpkS7WR5f0ddqw5quethTUn9WM+2g=go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=@@ -292,6 +323,8 @@ golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhgolang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=golang.org/x/crypto v0.51.0 h1:IBPXwPfKxY7cWQZ38ZCIRPI50YLeevDLlLnyC5wRGTI=golang.org/x/crypto v0.51.0/go.mod h1:8AdwkbraGNABw2kOX6YFPs3WM22XqI4EXEd8g+x7Oc8=+golang.org/x/exp v0.0.0-20260112195511-716be5621a96 h1:Z/6YuSHTLOHfNFdb8zVZomZr7cqNgTJvA8+Qz75D8gU=+golang.org/x/exp v0.0.0-20260112195511-716be5621a96/go.mod h1:nzimsREAkjBCIEFtHiYkrJyT+2uy9YZJB7H1k68CXZU=golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=golang.org/x/mod v0.35.0 h1:Ww1D637e6Pg+Zb2KrWfHQUnH2dQRLBQyAtpr/haaJeM=@@ -313,16 +346,15 @@ golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=-golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=-golang.org/x/sys v0.0.0-20211007075335-d3039528d8ac/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=-golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY=golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=+golang.org/x/telemetry v0.0.0-20260409153401-be6f6cb8b1fa h1:efT73AJZfAAUV7SOip6pWGkwJDzIGiKBZGVzHYa+ve4=+golang.org/x/telemetry v0.0.0-20260409153401-be6f6cb8b1fa/go.mod h1:kHjTxDEnAu6/Nl9lDkzjWpR+bmKfxeiRuSDlsMb70gE=golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=@@ -333,7 +365,6 @@ golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=-golang.org/x/tools v0.0.0-20201124115921-2c860bdd6e78/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=golang.org/x/tools v0.44.0 h1:UP4ajHPIcuMjT1GqzDWRlalUEoY+uzoZKnhOjbIPD2c=golang.org/x/tools v0.44.0/go.mod h1:KA0AfVErSdxRZIsOVipbv3rQhVXTnlU6UhKxHd1seDI=@@ -341,6 +372,8 @@ golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8Tgolang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=+golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da h1:noIWHXmPHxILtqtCOPIhSt0ABwskkZKjD3bXGnZGpNY=+golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da/go.mod h1:NDW/Ps6MPRej6fsCIbMTohpP40sJ/P/vI1MoTEGwX90=gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=google.golang.org/genproto/googleapis/api v0.0.0-20260226221140-a57be14db171 h1:tu/dtnW1o3wfaxCOjSLn5IRX4YDcJrtlpzYkhHhGaC4=@@ -360,39 +393,19 @@ gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVgopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=-lukechampine.com/uint128 v1.1.1/go.mod h1:c4eWIwlEGaxC/+H1VguhU4PHXNWDCDMUlWdIWl2j1gk=-lukechampine.com/uint128 v1.2.0 h1:mBi/5l91vocEN8otkC5bDLhi2KdCticRiwbdB0O+rjI=-lukechampine.com/uint128 v1.2.0/go.mod h1:c4eWIwlEGaxC/+H1VguhU4PHXNWDCDMUlWdIWl2j1gk=-modernc.org/cc/v3 v3.36.2/go.mod h1:NFUHyPn4ekoC/JHeZFfZurN6ixxawE1BnVonP/oahEI=-modernc.org/cc/v3 v3.36.3 h1:uISP3F66UlixxWEcKuIWERa4TwrZENHSL8tWxZz8bHg=-modernc.org/cc/v3 v3.36.3/go.mod h1:NFUHyPn4ekoC/JHeZFfZurN6ixxawE1BnVonP/oahEI=-modernc.org/ccgo/v3 v3.16.9 h1:AXquSwg7GuMk11pIdw7fmO1Y/ybgazVkMhsZWCV0mHM=-modernc.org/ccgo/v3 v3.16.9/go.mod h1:zNMzC9A9xeNUepy6KuZBbugn3c0Mc9TeiJO4lgvkJDo=-modernc.org/ccorpus v1.11.6 h1:J16RXiiqiCgua6+ZvQot4yUuUy8zxgqbqEEUuGPlISk=-modernc.org/ccorpus v1.11.6/go.mod h1:2gEUTrWqdpH2pXsmTM1ZkjeSrUWDpjMu2T6m29L/ErQ=-modernc.org/httpfs v1.0.6 h1:AAgIpFZRXuYnkjftxTAZwMIiwEqAfk8aVB2/oA6nAeM=-modernc.org/httpfs v1.0.6/go.mod h1:7dosgurJGp0sPaRanU53W4xZYKh14wfzX420oZADeHM=-modernc.org/libc v1.17.0/go.mod h1:XsgLldpP4aWlPlsjqKRdHPqCxCjISdHfM/yeWC5GyW0=-modernc.org/libc v1.17.1 h1:Q8/Cpi36V/QBfuQaFVeisEBs3WqoGAJprZzmf7TfEYI=-modernc.org/libc v1.17.1/go.mod h1:FZ23b+8LjxZs7XtFMbSzL/EhPxNbfZbErxEHc7cbD9s=-modernc.org/mathutil v1.2.2/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E=-modernc.org/mathutil v1.4.1/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E=-modernc.org/mathutil v1.5.0 h1:rV0Ko/6SfM+8G+yKiyI830l3Wuz1zRutdslNoQ0kfiQ=-modernc.org/mathutil v1.5.0/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E=-modernc.org/memory v1.2.0/go.mod h1:/0wo5ibyrQiaoUoH7f9D8dnglAmILJ5/cxZlRECf+Nw=-modernc.org/memory v1.2.1 h1:dkRh86wgmq/bJu2cAS2oqBCz/KsMZU7TUM4CibQ7eBs=-modernc.org/memory v1.2.1/go.mod h1:PkUhL0Mugw21sHPeskwZW4D6VscE/GQJOnIpCnW6pSU=-modernc.org/opt v0.1.1/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0=-modernc.org/opt v0.1.3 h1:3XOZf2yznlhC+ibLltsDGzABUGVx8J6pnFMS3E4dcq4=-modernc.org/opt v0.1.3/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0=-modernc.org/sqlite v1.18.1 h1:ko32eKt3jf7eqIkCgPAeHMBXw3riNSLhl2f3loEF7o8=-modernc.org/sqlite v1.18.1/go.mod h1:6ho+Gow7oX5V+OiOQ6Tr4xeqbx13UZ6t+Fw9IRUG4d4=-modernc.org/strutil v1.1.1/go.mod h1:DE+MQQ/hjKBZS2zNInV5hhcipt5rLPWkmpbGeW5mmdw=-modernc.org/strutil v1.1.3 h1:fNMm+oJklMGYfU9Ylcywl0CO5O6nTfaowNsh2wpPjzY=-modernc.org/strutil v1.1.3/go.mod h1:MEHNA7PdEnEwLvspRMtWTNnp2nnyvMfkimT1NKNAGbw=-modernc.org/tcl v1.13.1 h1:npxzTwFTZYM8ghWicVIX1cRWzj7Nd8i6AqqX2p+IYao=-modernc.org/tcl v1.13.1/go.mod h1:XOLfOwzhkljL4itZkK6T72ckMgvj0BDsnKNdZVUOecw=-modernc.org/token v1.0.0 h1:a0jaWiNMDhDUtqOj09wvjWWAqd3q7WpBulmL9H2egsk=-modernc.org/token v1.0.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=-modernc.org/z v1.5.1 h1:RTNHdsrOpeoSeOF4FbzTo8gBYByaJ5xT7NgZ9ZqRiJM=-modernc.org/z v1.5.1/go.mod h1:eWFB510QWW5Th9YGZT81s+LwvaAs3Q2yr4sP0rmLkv8=+modernc.org/fileutil v1.3.0 h1:gQ5SIzK3H9kdfai/5x41oQiKValumqNTDXMvKo62HvE=+modernc.org/fileutil v1.3.0/go.mod h1:XatxS8fZi3pS8/hKG2GH/ArUogfxjpEKs3Ku3aK4JyQ=+modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 h1:5D53IMaUuA5InSeMu9eJtlQXS2NxAhyWQvkKEgXZhHI=+modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6/go.mod h1:Qz0X07sNOR1jWYCrJMEnbW/X55x206Q7Vt4mz6/wHp4=+modernc.org/libc v1.41.0 h1:g9YAc6BkKlgORsUWj+JwqoB1wU3o4DE3bM3yvA3k+Gk=+modernc.org/libc v1.41.0/go.mod h1:w0eszPsiXoOnoMJgrXjglgLuDy/bt5RR4y3QzUUeodY=+modernc.org/mathutil v1.6.0 h1:fRe9+AmYlaej+64JsEEhoWuAYBkOtQiMEU7n/XgfYi4=+modernc.org/mathutil v1.6.0/go.mod h1:Ui5Q9q1TR2gFm0AQRqQUaBWFLAhQpCwNcuhBOSedWPo=+modernc.org/memory v1.7.2 h1:Klh90S215mmH8c9gO98QxQFsY+W451E8AnzjoE2ee1E=+modernc.org/memory v1.7.2/go.mod h1:NO4NVCQy0N7ln+T9ngWqOQfi7ley4vpwvARR+Hjw95E=+modernc.org/sqlite v1.29.6 h1:0lOXGrycJPptfHDuohfYgNqoe4hu+gYuN/pKgY5XjS4=+modernc.org/sqlite v1.29.6/go.mod h1:S02dvcmm7TnTRvGhv8IGYyLnIt7AS2KPaB1F/71p75U=+modernc.org/strutil v1.2.0 h1:agBi9dp1I+eOnxXeiZawM8F4LawKv4NzGWSaLfyeNZA=+modernc.org/strutil v1.2.0/go.mod h1:/mdcBmfOibveCTBxUl5B5l6W+TTH1FXPLHZE6bTosX0=+modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=+modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=diff --git a/cli/test/contract/seed_test.go b/cli/test/contract/seed_test.goindex 6a220796..54ec365f 100644--- a/cli/test/contract/seed_test.go+++ b/cli/test/contract/seed_test.go@@ -9,7 +9,7 @@ import ("github.com/tracewayapp/traceway/backend/app/controllers/clientcontrollers""github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/repositories"+ "github.com/tracewayapp/traceway/backend/app/repositories/telemetry")// Seeded ids, set by seedTelemetry and used to address the by-id detail@@ -68,7 +68,7 @@ func seedTelemetry(ctx context.Context, projectIDStr string, at time.Time) errorSpanId: &seedSpanID,IsRoot: true,}- if err := repositories.EndpointRepository.InsertAsync(ctx, []models.Endpoint{endpoint}); err != nil {+ if err := telemetry.EndpointRepository.InsertAsync(ctx, []models.Endpoint{endpoint}); err != nil {return fmt.Errorf("endpoint: %w", err)}@@ -85,7 +85,7 @@ func seedTelemetry(ctx context.Context, projectIDStr string, at time.Time) errorDistributedTraceId: &seedTraceID,IsRoot: true,}- if err := repositories.TaskRepository.InsertAsync(ctx, []models.Task{task}); err != nil {+ if err := telemetry.TaskRepository.InsertAsync(ctx, []models.Task{task}); err != nil {return fmt.Errorf("task: %w", err)}@@ -104,7 +104,7 @@ func seedTelemetry(ctx context.Context, projectIDStr string, at time.Time) errorDistributedTraceId: &seedTraceID,SessionId: &seedSessionID,}- if err := repositories.ExceptionStackTraceRepository.InsertAsync(ctx, []models.ExceptionStackTrace{exception}); err != nil {+ if err := telemetry.ExceptionStackTraceRepository.InsertAsync(ctx, []models.ExceptionStackTrace{exception}); err != nil {return fmt.Errorf("exception: %w", err)}@@ -118,7 +118,7 @@ func seedTelemetry(ctx context.Context, projectIDStr string, at time.Time) errorRecordedAt: at,Attributes: map[string]string{},}- if err := repositories.SpanRepository.InsertAsync(ctx, []models.Span{span}); err != nil {+ if err := telemetry.SpanRepository.InsertAsync(ctx, []models.Span{span}); err != nil {return fmt.Errorf("span: %w", err)}@@ -129,7 +129,7 @@ func seedTelemetry(ctx context.Context, projectIDStr string, at time.Time) errorTags: map[string]string{},RecordedAt: at,}- if err := repositories.MetricPointRepository.InsertAsync(ctx, []models.MetricPoint{metric}); err != nil {+ if err := telemetry.MetricPointRepository.InsertAsync(ctx, []models.MetricPoint{metric}); err != nil {return fmt.Errorf("metric: %w", err)}@@ -144,7 +144,7 @@ func seedTelemetry(ctx context.Context, projectIDStr string, at time.Time) errorServerName: "contract-host",DistributedTraceId: &seedTraceID,}- if err := repositories.SessionRepository.Upsert(ctx, []models.Session{session}); err != nil {+ if err := telemetry.SessionRepository.Upsert(ctx, []models.Session{session}); err != nil {return fmt.Errorf("session: %w", err)}@@ -167,7 +167,7 @@ func seedTelemetry(ctx context.Context, projectIDStr string, at time.Time) errorDistributedTraceId: &seedTraceID,IsRoot: true,}- if err := repositories.AiTraceRepository.InsertAsync(ctx, []models.AiTrace{aiTrace}); err != nil {+ if err := telemetry.AiTraceRepository.InsertAsync(ctx, []models.AiTrace{aiTrace}); err != nil {return fmt.Errorf("ai trace: %w", err)}@@ -183,7 +183,7 @@ func seedTelemetry(ctx context.Context, projectIDStr string, at time.Time) errorScopeAttributes: map[string]string{},LogAttributes: map[string]string{},}- if err := repositories.LogRecordRepository.InsertAsync(ctx, []models.LogRecord{logRecord}); err != nil {+ if err := telemetry.LogRecordRepository.InsertAsync(ctx, []models.LogRecord{logRecord}); err != nil {return fmt.Errorf("log: %w", err)}diff --git a/docs/pages/learn/build-tags.mdx b/docs/pages/learn/build-tags.mdxindex 161fc37a..cce7ba07 100644--- a/docs/pages/learn/build-tags.mdx+++ b/docs/pages/learn/build-tags.mdx@@ -1,15 +1,42 @@# Build Tags-The Traceway backend uses Go build tags to switch between storage backends and to embed the frontend.+The Traceway backend uses Go build tags to switch between storage backends and to embed the frontend. Storage is selected on two independent axes: the **telemetry** store (high-volume, append-only data) and the **transactional** store (relational/config data).## Tags+### Telemetry axis++| Tag | Purpose |+|-----|---------|+| *(none)* / `telemetry_sqlite` | **SQLite** telemetry store — embedded mode. This is the default; `telemetry_sqlite` is accepted as an explicit no-op spelling. |+| `telemetry_duckdb` | **DuckDB** telemetry store — embedded mode with a columnar engine for much faster dashboard analytics. Requires `CGO_ENABLED=1`. |+| `telemetry_ch` | **ClickHouse** telemetry store — standalone server mode. |++### Transactional axis++| Tag | Purpose |+|-----|---------|+| *(none)* / `transactional_sqlite` | **SQLite** main database. This is the default; `transactional_sqlite` is accepted as an explicit no-op spelling. |+| `transactional_pg` | **PostgreSQL** main database — standalone server mode. |++### Other+| Tag | Purpose ||-----|---------|-| *(none)* | **SQLite** storage — embedded mode, zero external dependencies. This is the default. |-| `pgch` | **ClickHouse + PostgreSQL** storage — standalone server mode. || `localdist` | Embeds frontend from `static/dist/` instead of `static/frontend/`. Used by traceway-cloud to inject billing UI into the frontend build. Not needed for open-source builds. |+## Supported combinations++Only three combinations are supported, enforced by compile-time guard files in `backend/app/db/` — an unsupported combination fails the build with a descriptive identifier in the error message:++| Mode | Tags | Databases |+|------|------|-----------|+| Embedded (default) | *(none)* | SQLite main + SQLite telemetry |+| Embedded, columnar telemetry | `telemetry_duckdb` | SQLite main + DuckDB telemetry |+| Standalone server | `transactional_pg telemetry_ch` | PostgreSQL main + ClickHouse telemetry |++The legacy `pgch` and `duckdb` tags were renamed to this scheme; passing them fails the build with a message pointing at the new tags, so a stale invocation cannot silently produce the wrong binary.+## Building### Embedded mode (SQLite)@@ -22,20 +49,28 @@ cd backend && go build ./cmd/tracewayThis is what library consumers get when they `go get github.com/tracewayapp/traceway/backend` and call `tracewaybackend.Run()`.+### Embedded mode with DuckDB telemetry++```bash+cd backend && CGO_ENABLED=1 go build -tags telemetry_duckdb ./cmd/traceway+```++DuckDB links prebuilt glibc static libraries, so this build needs CGO and a glibc-based image (Debian, not Alpine) when containerized — see `Dockerfile.duckdb`.+### Standalone server (ClickHouse + PostgreSQL)```bash-cd backend && go build -tags pgch ./cmd/traceway+cd backend && go build -tags "transactional_pg telemetry_ch" ./cmd/traceway```Requires `CLICKHOUSE_SERVER`, `POSTGRES_HOST`, and the other environment variables to be configured.### Docker image-The Dockerfiles build the frontend and embed it into the Go binary with the `pgch` tag:+The Dockerfiles build the frontend and embed it into the Go binary with the standalone tags:```bash-go build -tags pgch ./cmd/traceway+go build -tags "transactional_pg telemetry_ch" ./cmd/traceway```The frontend is embedded from `static/frontend/` which the Docker build populates from the SvelteKit build output. You don't need to embed the frontend for local development — run the frontend dev server separately with `cd frontend && npm run dev`.@@ -45,13 +80,19 @@ The frontend is embedded from `static/frontend/` which the Docker build populate### SQLite tests (default)```bash-cd backend && go test -v -count=1 ./app/repositories/+cd backend && go test -v -count=1 ./app/repositories/...+```++### DuckDB tests++```bash+cd backend && CGO_ENABLED=1 go test -tags telemetry_duckdb -v -count=1 ./app/repositories/...```### ClickHouse tests```bash-cd backend && TEST_CLICKHOUSE_SERVER=localhost:9000 go test -tags pgch -v ./app/repositories/+cd backend && TEST_CLICKHOUSE_SERVER=localhost:9000 go test -tags "transactional_pg telemetry_ch" -v ./app/repositories/...```-Without `TEST_CLICKHOUSE_SERVER` set, the `pgch` tests skip cleanly.+Without `TEST_CLICKHOUSE_SERVER` set, the ClickHouse tests skip cleanly.diff --git a/docs/pages/learn/contributing.mdx b/docs/pages/learn/contributing.mdxindex 5ec61464..350111e9 100644--- a/docs/pages/learn/contributing.mdx+++ b/docs/pages/learn/contributing.mdx@@ -53,7 +53,7 @@ Maintainers add labels after the issue is filed. You don't need to set them your- **Go** 1.25 or later- **Node.js** 18+ and npm-- **Docker** (for running the full pgch test suite)+- **Docker** (for running the full ClickHouse + PostgreSQL test suite)- **ClickHouse** and **PostgreSQL** (only if running the standalone server locally — not needed for embedded/SQLite mode)## Build Tags@@ -63,7 +63,8 @@ Traceway uses Go build tags to switch between storage backends:| Tag | Purpose ||-----|---------|| *(none)* | **SQLite** — embedded mode, zero dependencies. This is the default. |-| `pgch` | **ClickHouse + PostgreSQL** — standalone server mode. |+| `telemetry_duckdb` | **DuckDB telemetry** — embedded mode with a columnar telemetry store. Requires `CGO_ENABLED=1`. |+| `transactional_pg telemetry_ch` | **ClickHouse + PostgreSQL** — standalone server mode. || `localdist` | Embeds the pre-built frontend into the Go binary. Used in Docker builds. |See the [Build Tags](/learn/build-tags) page for more details.@@ -88,8 +89,8 @@ If you're working on ClickHouse or PostgreSQL-specific code, see the [Local Setu```bashcd backend-go build -tags pgch ./...-go run -tags pgch ./cmd/traceway+go build -tags "transactional_pg telemetry_ch" ./...+go run -tags "transactional_pg telemetry_ch" ./cmd/traceway```### Frontend@@ -118,21 +119,21 @@ These run without any external dependencies:```bashcd backend-go test -v -count=1 ./app/repositories/+go test -v -count=1 ./app/repositories/...```### ClickHouse + PostgreSQL tests (via Docker)-The full pgch test suite runs ClickHouse and PostgreSQL inside a Docker container. This is the most reliable way to verify ClickHouse-specific code:+The full ClickHouse + PostgreSQL test suite runs both databases inside a Docker container. This is the most reliable way to verify ClickHouse-specific code:```bash./scripts/test-backend-pgch.sh```-This builds a Docker image with both databases, applies all migrations, and runs the test suite with `-tags pgch`. All tests should pass.+This builds a Docker image with both databases, applies all migrations, and runs the test suite with `-tags "transactional_pg telemetry_ch"`. All tests should pass.<Callout type="info">- Without Docker, you can run pgch tests against local databases by setting environment variables:+ Without Docker, you can run the ClickHouse + PostgreSQL tests against local databases by setting environment variables:```bashcd backend@@ -142,10 +143,10 @@ This builds a Docker image with both databases, applies all migrations, and runsTEST_POSTGRES_DATABASE=traceway_test \TEST_POSTGRES_USERNAME=traceway \TEST_POSTGRES_PASSWORD=traceway \- go test -tags pgch -v -count=1 ./app/repositories/+ go test -tags "transactional_pg telemetry_ch" -v -count=1 ./app/repositories/...```- Without `TEST_CLICKHOUSE_SERVER` set, the pgch tests skip cleanly.+ Without `TEST_CLICKHOUSE_SERVER` set, the ClickHouse tests skip cleanly.</Callout>### OTEL trace converter tests@@ -200,7 +201,7 @@ Two separate auth systems:### Backend Patterns-**Repositories** are singletons (`var FooRepository = fooRepository{}`). Each repository has two implementations in separate files — one for ClickHouse/PostgreSQL (`//go:build pgch`) and one for SQLite (`//go:build !pgch`).+**Repositories** are singletons (`var FooRepository = &fooRepository{}`) organized on the two storage axes. Telemetry repositories have one implementation per backend under `backend/app/repositories/telemetry/{clickhouse,sqlite,duckdb}/`, selected by the `telemetry_*` build tags; transactional (relational) repositories live under `backend/app/repositories/transactional/{pg,sqlite}/`, selected by the `transactional_*` build tags. Each axis is re-exported through its facade package — callers import `app/repositories/telemetry` or `app/repositories/transactional` (e.g. `telemetry.SpanRepository`, `transactional.UserRepository`) and never a backend package directly.**Controllers** use the Gin framework. PostgreSQL operations go through `middleware.Transactional` for automatic commit/rollback.@@ -243,18 +244,19 @@ git checkout -b your-feature upstream/main### Before submitting-1. **Build both backends** to make sure nothing is broken:+1. **Build all backends** to make sure nothing is broken:```bashcd backend-go build ./... # SQLite (default)-go build -tags pgch ./... # ClickHouse + PostgreSQL+go build ./... # SQLite (default)+go build -tags "transactional_pg telemetry_ch" ./... # ClickHouse + PostgreSQL+CGO_ENABLED=1 go build -tags telemetry_duckdb ./... # DuckDB telemetry```2. **Run the SQLite tests**:```bash-go test -v -count=1 ./app/repositories/+go test -v -count=1 ./app/repositories/...```3. **Run the OTEL converter tests** if you changed any OTEL parsing code:@@ -263,7 +265,7 @@ go test -v -count=1 ./app/repositories/go test -v -count=1 ./app/controllers/otelcontrollers/```-4. **Run the pgch Docker tests** if you changed any repository code:+4. **Run the ClickHouse + PostgreSQL Docker tests** if you changed any repository code:```bash./scripts/test-backend-pgch.sh@@ -305,7 +307,7 @@ All pull requests require **at least one approving review** before merging. This### What reviewers look at- **Correctness** — does the code do what the PR says it does?-- **Testing** — are the requirements in "Before submitting" met? Repository changes need the pgch Docker tests to pass.+- **Testing** — are the requirements in "Before submitting" met? Repository changes need the ClickHouse + PostgreSQL Docker tests to pass.- **Patterns** — does the change follow the conventions in [CLAUDE.md](https://github.com/tracewayapp/traceway/blob/main/CLAUDE.md)? Reviewers will push back on divergence from established patterns.- **Scope** — is the PR focused? A small, focused PR is always preferred over one that mixes unrelated changes.diff --git a/docs/pages/learn/hardware-requirements.mdx b/docs/pages/learn/hardware-requirements.mdxindex 10545f56..79198e84 100644--- a/docs/pages/learn/hardware-requirements.mdx+++ b/docs/pages/learn/hardware-requirements.mdx@@ -2,18 +2,20 @@import { Callout } from "nextra/components";-How much CPU, RAM, and disk Traceway needs depends almost entirely on **which storage backend you run**. The backend ships as a single static Go binary (CGO disabled, frontend embedded), so the binary itself is cheap. What costs memory is the database next to it.+How much CPU, RAM, and disk Traceway needs depends almost entirely on **which storage backend you run**. The backend ships as a single Go binary with the frontend embedded (static and CGO-free except in DuckDB mode, which links the DuckDB engine), so the binary itself is cheap. What costs memory is the database next to it.-There are two shapes:+There are three shapes:- **SQLite mode** (single binary, zero external dependencies). The whole stack is one process. This is the lightweight option.-- **ClickHouse + PostgreSQL mode** (`pgch`). ClickHouse is built to use a lot of RAM for caches and merges, so this is the heavier option that scales much further.+- **DuckDB mode** (`telemetry_duckdb` build tag, CGO required). Still a single container with zero external dependencies, but the telemetry store is DuckDB's columnar engine, which holds 10 to 100 times more queryable rows than SQLite on the same box. The catch: DuckDB sizes itself from host RAM, so memory-capped containers must set `DUCKDB_MEMORY_LIMIT`.+- **ClickHouse + PostgreSQL mode** (`transactional_pg telemetry_ch` build tags). ClickHouse is built to use a lot of RAM for caches and merges, so this is the heavier option that scales much further.## TL;DR| Deployment | Minimum to start | Comfortable | Notes ||------------|------------------|-------------|-------|| **SQLite** (single binary) | 1 vCPU, 512 MB RAM | 2 vCPU, 1 to 2 GB RAM | The backend process idles at ~30 MB RSS. Memory grows with the SQLite page cache and source map cache, both capped. |+| **DuckDB** (single container) | 2 vCPU, 2 GB RAM, `DUCKDB_MEMORY_LIMIT` set | 2 to 4 vCPU, 4 to 8 GB RAM | DuckDB auto-tunes to ~80% of what it thinks is host RAM. In a memory-capped container it reads the host, not the cgroup, so set `DUCKDB_MEMORY_LIMIT` explicitly or the backend gets OOM-killed under ingest. || **ClickHouse + PostgreSQL** | 2 vCPU, 4 GB RAM | 4 vCPU, 8 GB+ RAM | ClickHouse is the floor here, not Traceway. It claims up to 80% of host RAM by design. |If you just want "the smallest box that runs it," that is the SQLite deployment, and it is genuinely small. The Go process is not where your money goes.@@ -59,9 +61,22 @@ We benchmark the single-binary SQLite build on dedicated Hetzner CCX instances,SQLite stores telemetry on local disk, so disk is the resource to watch, not RAM. Size it for your retention window. Telemetry rows are pruned by a background worker (`SQLITE_RETENTION_DAYS`, default 30); see [Data retention on the SQLite page](/server/sqlite#configuration). Blob storage (source maps, session recordings, AI traces) lives under the same `/data` volume unless you offload it to S3.+## DuckDB mode (the small one that reads big)++The DuckDB deployment (`Dockerfile.duckdb`) keeps the single-container shape: the main DB stays SQLite, only the telemetry store becomes DuckDB. You get the same zero-dependency operations with dramatically more read headroom - on a 2 vCPU / 8 GB box the metrics dashboard stays under the 5 s threshold at 100M stored points, where SQLite cliffs around 1M.++Two things differ from the SQLite sizing story:++- **Memory is the knob to set, not to ignore.** DuckDB auto-tunes its memory budget to ~80% of RAM, and inside a container it sees the host's RAM, not the container limit. On any memory-capped deployment, set `DUCKDB_MEMORY_LIMIT` (for example `2GB` on a 4 GB container) and optionally `DUCKDB_THREADS`. An uncapped DuckDB on a capped container is the one configuration that reliably OOM-kills the backend.+- **The image is Debian, not Alpine.** The DuckDB driver bundles glibc static libraries, so this build cannot run on musl-based images.++Under sustained ingest, `DUCKDB_CHECKPOINT_THRESHOLD` (default 16MB) can be raised to reduce WAL checkpoint stalls at the cost of a larger WAL and longer restart replay.++Disk behaves like the SQLite story above (same retention worker, same `/data` volume), but columnar compression makes the telemetry file several times smaller for the same rows.+## ClickHouse + PostgreSQL mode-The [Docker Compose](/server/docker-compose), [all-in-one](/server/all-in-one), and [minimal](/server/minimal) deployments run the `pgch` build against ClickHouse (telemetry) and PostgreSQL (config). Here the hardware floor is set by **ClickHouse**, not by the Traceway backend.+The [Docker Compose](/server/docker-compose), [all-in-one](/server/all-in-one), and [minimal](/server/minimal) deployments run the `transactional_pg telemetry_ch` build against ClickHouse (telemetry) and PostgreSQL (config). Here the hardware floor is set by **ClickHouse**, not by the Traceway backend.ClickHouse is designed to use memory aggressively. In the bundled config it claims up to **80% of host RAM** (`max_server_memory_usage_to_ram_ratio = 0.8`) for query and merge buffers, and reserves a multi-GB mark cache. Plan around that, not around the Go process:@@ -84,6 +99,7 @@ If you are sizing a small box, these are the knobs that matter. Every one has a| Source map cache (in memory) | 500 MB cap, 200 resolvers | `SOURCEMAP_CACHE_MAX_BYTES_MB`, `SOURCEMAP_CACHE_MAX_ENTRIES` | JS/TS projects that upload source maps. On a 1 to 2 GB box, set the cap to `100`. || Source map cache (disk tier) | off | `SOURCEMAP_CACHE_TYPE=disk`, `SOURCEMAP_DISK_CACHE_MAX_MB` (2048) | Many active maps, or multiple backend instances. Moves `.tw` resolvers to memory-mapped files. || SQLite page cache | ~512 MB cap | `cache_size` pragma | SQLite mode under sustained ingest. A ceiling, grown on demand. |+| DuckDB memory budget | ~80% of host RAM | `DUCKDB_MEMORY_LIMIT`, `DUCKDB_THREADS` | DuckDB mode. Mandatory in memory-capped containers - DuckDB sizes itself from the host, not the cgroup. || Session-recording uploader | 32 workers, 2048 queue | `SESSION_RECORDING_UPLOAD_WORKERS`, `SESSION_RECORDING_UPLOAD_QUEUE_SIZE` | Browser/mobile session replay. Set workers to `0` to disable entirely. |On a memory-constrained host, the single most effective change is lowering `SOURCEMAP_CACHE_MAX_BYTES_MB`. The source map cache is the largest tunable consumer, because resolving a minified stack frame means holding a built resolver in memory.@@ -100,5 +116,6 @@ On a memory-constrained host, the single most effective change is lowering `SOUR- **"I want the cheapest thing that runs."** SQLite mode, 1 vCPU / 512 MB. It idles around 30 MB and the caches are capped.- **"Small production app, some JS source maps."** SQLite mode, 2 vCPU / 1 to 2 GB, source map cap at 100 to 250 MB.+- **"Single container, but the dashboards got slow as data grew."** DuckDB mode, 2 to 4 vCPU / 4 to 8 GB, with `DUCKDB_MEMORY_LIMIT` set to roughly half the container's RAM.- **"High ingest, long retention, want it to scale."** ClickHouse + PostgreSQL, 4 vCPU / 8 GB+, and size ClickHouse first.- **"It's getting slow."** Don't guess. Turn on [self-monitoring](/server/capacity-monitoring) and let the metrics tell you whether to scale ClickHouse, scale the backend, or buffer ingestion.diff --git a/scripts/test-pgch-entrypoint.sh b/scripts/test-pgch-entrypoint.shindex fc7220a4..229b335e 100755--- a/scripts/test-pgch-entrypoint.sh+++ b/scripts/test-pgch-entrypoint.sh@@ -61,4 +61,4 @@ TEST_POSTGRES_HOST=localhost \TEST_POSTGRES_DATABASE=traceway_test \TEST_POSTGRES_USERNAME=traceway \TEST_POSTGRES_PASSWORD=traceway \-go test -tags pgch -v -count=1 ./app/repositories/+go test -tags "transactional_pg telemetry_ch" -v -count=1 ./app/repositories/...