diff --git a/.changeset/alchemy-sourcemaps.md b/.changeset/alchemy-sourcemaps.md new file mode 100644 index 0000000000..bd20b3cf0a --- /dev/null +++ b/.changeset/alchemy-sourcemaps.md @@ -0,0 +1,5 @@ +--- +"@maple-dev/alchemy": minor +--- + +Automatic source map uploads. `@maple-dev/alchemy/vite` exports `mapleSourceMaps()`, a Vite plugin that turns on hidden source maps, gives each built JS file a debug id and moves the maps out of the deployed output into `.maple/sourcemaps/` with a manifest. The new `Maple.SourceMaps` resource uploads them through `POST /v2/source_maps` after the build, again only when the maps changed; deleting it keeps the uploaded maps, which earlier releases still need. `matchBy: "release"` uploads without debug ids, for telemetry that reports none. `MapleApiContract` gains `upload` for raw request bodies. diff --git a/.changeset/browser-exception-debug-ids.md b/.changeset/browser-exception-debug-ids.md new file mode 100644 index 0000000000..a5c61513b4 --- /dev/null +++ b/.changeset/browser-exception-debug-ids.md @@ -0,0 +1,5 @@ +--- +"@maple-dev/browser": minor +--- + +Exception events now carry `maple.exception.debug_ids`: for each script in the error's stack that registered a debug id (through `maple sourcemaps inject`, or Sentry's debug id tooling), its URL and id, so the matching source map is found by id rather than by file path. Absent when no script in the stack has one. diff --git a/.changeset/cli-sourcemaps.md b/.changeset/cli-sourcemaps.md new file mode 100644 index 0000000000..b7485c782f --- /dev/null +++ b/.changeset/cli-sourcemaps.md @@ -0,0 +1,5 @@ +--- +"@maple/cli": minor +--- + +New `maple sourcemaps inject ` and `maple sourcemaps upload `. `inject` gives every built JS file that has a source map a debug id (derived from the file and its map, so re-running changes nothing), registers it on the file's first line so errors thrown while the file loads still carry it, and writes it into the map; `--dry-run` reports without writing. Maps outside the build directory are never touched. `upload` sends each map to the logged-in workspace, once per JS file that uses it, matched by debug id or by `--service`, `--release` (defaults to the build directory's git commit) and the file path, with `--url-prefix` for the path the files are served under. Maps over 10 MiB (the largest Maple can symbolicate with) and index maps (`sections`) are skipped with a warning, and a run that uploads nothing fails. diff --git a/.gitignore b/.gitignore index 5433fe2984..9de8e42fd7 100644 --- a/.gitignore +++ b/.gitignore @@ -81,3 +81,6 @@ apps/ios/build/ scripts/seed-demo/.last-seed.json # isolated screenshot stack env, generated by bun run seed:demo:env .env.screenshots + +# Source maps the Vite plugin moves out of a build (`@maple-dev/alchemy/vite`). +.maple/ diff --git a/alchemy.run.ts b/alchemy.run.ts index 77ec2d8999..f4a4b880b6 100644 --- a/alchemy.run.ts +++ b/alchemy.run.ts @@ -47,6 +47,7 @@ import { createAwsSecurityBaseline } from "@maple/infra/security-baseline" import { optionalPlain, plainWithDefault, requiredPlain } from "@maple/infra/env" import * as Portless from "@maple/alchemy-portless" import { DEV_PROCESS_APPS, selectedDevApps, type DevApp } from "@maple/infra/dev-urls" +import { selfMapleProviders, uploadWebSourceMaps } from "@maple/infra/self-source-maps" import MapleAiLive, { MapleAi } from "./apps/ai/src/worker.ts" import Alerting from "./apps/alerting/src/worker.ts" import OrgEraser from "./apps/org-eraser/src/worker.ts" @@ -62,6 +63,8 @@ import { createMapleScraper } from "./apps/scraper/alchemy.run.ts" import Landing from "./apps/landing/src/worker.ts" import LocalUi from "./apps/local-ui/src/worker.ts" import Web from "./apps/web/src/worker.ts" +import { WEB_SERVICE_NAME } from "./apps/web/src/platform/service-identity.ts" +import { WEB_SOURCE_MAPS_DIR } from "./apps/web/source-maps-dir.ts" import { Array as Arr } from "effect" // Infisical defines CLOUDFLARE_DEFAULT_ACCOUNT_ID; alchemy reads CLOUDFLARE_ACCOUNT_ID. @@ -324,6 +327,8 @@ const providers = // Previews only; prd and dev deploys carry no NEON_API_KEY. Layer.provideMerge(!isDevServer && process.env.NEON_API_KEY ? Neon.providers() : Layer.empty), Layer.provideMerge(Portless.providers()), + // Uploads web's source maps; inert without the prd-only key. + Layer.provideMerge(selfMapleProviders), ) export default Alchemy.Stack( @@ -429,6 +434,14 @@ export default Alchemy.Stack( // A vite-source Worker: alchemy owns its build and dev server. Binds api as `API`. const web = yield* Effect.provideService(Web, ApiWorker, api) yield* serveWorker("web", web) + // Its source maps, moved out of the deployed assets by the Vite plugin (apps/web/vite.config.ts), + // uploaded after the build under the service and release its telemetry reports. + if (!isDevServer) + yield* uploadWebSourceMaps({ + dir: path.resolve(import.meta.dirname, WEB_SOURCE_MAPS_DIR), + service: WEB_SERVICE_NAME, + after: web.hash, + }) // StaticSites run their production build even on `alchemy dev`, so dev uses // `DEV_PROCESS_APPS` instead. Shared across instances: deployed by `us` alone. diff --git a/apps/ai/src/mcp/tool-descriptors.generated.ts b/apps/ai/src/mcp/tool-descriptors.generated.ts index 0107c45850..f52ff6b516 100644 --- a/apps/ai/src/mcp/tool-descriptors.generated.ts +++ b/apps/ai/src/mcp/tool-descriptors.generated.ts @@ -116,7 +116,7 @@ export const MCP_TOOL_DESCRIPTORS: ReadonlyArray = [ {"name":"transition_error_issues","title":"Transition Error Issues","description":"Batch form of transition_error_issue, same rules: up to 200 issues to one state, one note on each. Each issue is checked on its own; a refused move or bad id fails only that issue.","inputSchema":{"type":"object","properties":{"issue_ids":{"type":"array","items":{"type":"string"},"description":"Error issue IDs from list_error_issues, at most 200"},"to_state":{"type":"string","enum":["triage","todo","in_progress","in_review","done","cancelled","wontfix"],"description":"Target state for every issue: triage, todo, in_progress, in_review, done, cancelled, wontfix"},"note":{"type":"string","description":"Reasoning or context, stored on every issue's timeline with the move"},"snooze_until":{"type":"string","description":"For a `wontfix` move: time after which new occurrences reopen each issue as `triage`, UTC (YYYY-MM-DD HH:mm:ss or ISO 8601)"}},"required":["issue_ids","to_state"],"additionalProperties":false},"outputSchema":{"type":"object","properties":{"toState":{"type":"string"},"succeeded":{"anyOf":[{"type":"number"},{"type":"string","enum":["Infinity","-Infinity","NaN"]}]},"failed":{"anyOf":[{"type":"number"},{"type":"string","enum":["Infinity","-Infinity","NaN"]}]},"results":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string"},"ok":{"type":"boolean"},"fromState":{"type":"string"},"workflowState":{"type":"string"},"error":{"type":"string"}},"required":["id","ok"],"additionalProperties":true}},"note":{"type":"string"}},"required":["toState","succeeded","failed","results"],"additionalProperties":true},"annotations":{"title":"Transition Error Issues","readOnlyHint":false,"destructiveHint":false,"idempotentHint":true,"openWorldHint":false}}, {"name":"set_issue_severity","title":"Set Issue Severity","description":"Set or clear the triage severity of an issue. Severity drives escalation routing. An agent identity writes with `ai` precedence and never overwrites a severity a human set by hand; the result says whether it applied. A human session writes a sticky manual override.","inputSchema":{"type":"object","properties":{"issue_id":{"type":"string","description":"The error issue ID from list_error_issues (a fingerprint from find_errors is not an issue id): its UUID or its REST id (iss_\u2026)"},"severity":{"type":"string","enum":["critical","high","medium","low","none"],"description":"Target severity; `none` clears it"},"note":{"type":"string","description":"Reasoning or context, stored on the severity event"}},"required":["issue_id","severity"],"additionalProperties":false},"outputSchema":{"type":"object","properties":{"id":{"type":"string"},"severity":{"anyOf":[{"type":"string"},{"type":"null"}]},"severitySource":{"anyOf":[{"type":"string"},{"type":"null"}]},"applied":{"type":"boolean"},"workflowState":{"type":"string"},"serviceName":{"type":"string"},"note":{"type":"string"}},"required":["id","severity","severitySource","applied","workflowState","serviceName"],"additionalProperties":true},"annotations":{"title":"Set Issue Severity","readOnlyHint":false,"destructiveHint":false,"idempotentHint":true,"openWorldHint":false}}, {"name":"merge_error_issues","title":"Merge Error Issues","description":"Fold duplicate error issues into one when they are the same bug split across fingerprints. The kept issue (issue_id) takes their occurrences and every future occurrence of their fingerprints; each merged issue is archived pointing at it. Up to 50 at a time. Only merge issues you have confirmed share a root cause; a merge is undone from the dashboard.","inputSchema":{"type":"object","properties":{"issue_id":{"type":"string","description":"The issue to keep, from list_error_issues: its UUID or its REST id (iss_\u2026)"},"merge_issue_ids":{"type":"array","items":{"type":"string"},"description":"Issue IDs to fold into it, at most 50"}},"required":["issue_id","merge_issue_ids"],"additionalProperties":false},"outputSchema":{"type":"object","properties":{"id":{"type":"string"},"mergedIssueIds":{"type":"array","items":{"type":"string"}},"fingerprintHashes":{"type":"array","items":{"type":"string"}},"occurrenceCount":{"anyOf":[{"type":"number"},{"type":"string","enum":["Infinity","-Infinity","NaN"]}]},"workflowState":{"type":"string"},"serviceName":{"type":"string"}},"required":["id","mergedIssueIds","fingerprintHashes","occurrenceCount","workflowState","serviceName"],"additionalProperties":true},"annotations":{"title":"Merge Error Issues","readOnlyHint":false,"destructiveHint":true,"idempotentHint":false,"openWorldHint":false}}, - {"name":"explain_error_grouping","title":"Explain Error Grouping","description":"Explain why an error issue holds the fingerprints it does: for each one, how it got there (the issue's own, a merge, a version re-key, or the grouping key) and which rule keyed it, with the message signature and the stack frames read and skipped. Use it when an issue looks like it mixes unrelated bugs.","inputSchema":{"type":"object","properties":{"issue_id":{"type":"string","description":"The error issue ID from list_error_issues (a fingerprint from find_errors is not an issue id): its UUID or its REST id (iss_\u2026)"}},"required":["issue_id"],"additionalProperties":false},"outputSchema":{"type":"object","properties":{"issueId":{"type":"string"},"fingerprints":{"type":"array","items":{"$ref":"#/$defs/ErrorIssueFingerprintGroupingEncoded"}},"truncated":{"type":"boolean"}},"required":["issueId","fingerprints","truncated"],"additionalProperties":true,"$defs":{"@maple/GroupingRule":{"type":"string","enum":["custom","span","org-rule","chunk-load","type-message","type-function","frames"],"title":"Grouping Rule"},"@maple/IsoDateTimeString":{"type":"string"},"ErrorIssueFingerprintGroupingEncoded":{"type":"object","properties":{"fingerprintHash":{"type":"string"},"source":{"type":"string","enum":["primary","merge","rekey","group"]},"rule":{"anyOf":[{"$ref":"#/$defs/@maple~1GroupingRule"},{"type":"null"}]},"orgRule":{"anyOf":[{"type":"string"},{"type":"null"}]},"pinned":{"type":"boolean"},"exceptionType":{"type":"string"},"messageSignature":{"type":"string"},"frames":{"type":"array","items":{"type":"string"}},"skippedFrames":{"type":"array","items":{"type":"string"}},"customKey":{"anyOf":[{"type":"string"},{"type":"null"}]},"sampledAt":{"anyOf":[{"$ref":"#/$defs/@maple~1IsoDateTimeString"},{"type":"null"}]}},"required":["fingerprintHash","source","rule","orgRule","pinned","exceptionType","messageSignature","frames","skippedFrames","customKey","sampledAt"],"additionalProperties":true}}},"annotations":{"title":"Explain Error Grouping","readOnlyHint":true,"destructiveHint":false,"idempotentHint":true,"openWorldHint":false}}, + {"name":"explain_error_grouping","title":"Explain Error Grouping","description":"Explain why an error issue holds the fingerprints it does: for each one, how it got there (the issue's own, a merge, a version re-key, or the grouping key) and which rule keyed it, with the message signature and the stack frames read and skipped. Use it when an issue looks like it mixes unrelated bugs.","inputSchema":{"type":"object","properties":{"issue_id":{"type":"string","description":"The error issue ID from list_error_issues (a fingerprint from find_errors is not an issue id): its UUID or its REST id (iss_\u2026)"}},"required":["issue_id"],"additionalProperties":false},"outputSchema":{"type":"object","properties":{"issueId":{"type":"string"},"fingerprints":{"type":"array","items":{"$ref":"#/$defs/ErrorIssueFingerprintGroupingEncoded"}},"truncated":{"type":"boolean"}},"required":["issueId","fingerprints","truncated"],"additionalProperties":true,"$defs":{"@maple/GroupingRule":{"type":"string","enum":["custom","span","org-rule","chunk-load","type-message","type-function","frames","source-mapped","source-mapped-function"],"title":"Grouping Rule"},"@maple/IsoDateTimeString":{"type":"string"},"ErrorIssueFingerprintGroupingEncoded":{"type":"object","properties":{"fingerprintHash":{"type":"string"},"source":{"type":"string","enum":["primary","merge","rekey","group"]},"rule":{"anyOf":[{"$ref":"#/$defs/@maple~1GroupingRule"},{"type":"null"}]},"orgRule":{"anyOf":[{"type":"string"},{"type":"null"}]},"pinned":{"type":"boolean"},"exceptionType":{"type":"string"},"messageSignature":{"type":"string"},"frames":{"type":"array","items":{"type":"string"}},"skippedFrames":{"type":"array","items":{"type":"string"}},"customKey":{"anyOf":[{"type":"string"},{"type":"null"}]},"sampledAt":{"anyOf":[{"$ref":"#/$defs/@maple~1IsoDateTimeString"},{"type":"null"}]}},"required":["fingerprintHash","source","rule","orgRule","pinned","exceptionType","messageSignature","frames","skippedFrames","customKey","sampledAt"],"additionalProperties":true}}},"annotations":{"title":"Explain Error Grouping","readOnlyHint":true,"destructiveHint":false,"idempotentHint":true,"openWorldHint":false}}, {"name":"list_similar_error_issues","title":"List Similar Error Issues","description":"List open issues that may be the same bug as this one: same service and error type, with a similar message, most similar first. These are suggestions only; check that each shares the root cause before merging it.","inputSchema":{"type":"object","properties":{"issue_id":{"type":"string","description":"The error issue ID from list_error_issues (a fingerprint from find_errors is not an issue id): its UUID or its REST id (iss_\u2026)"}},"required":["issue_id"],"additionalProperties":false},"outputSchema":{"type":"object","properties":{"issueId":{"type":"string"},"issues":{"type":"array","items":{"$ref":"#/$defs/ErrorIssueSimilarIssueEncoded"}}},"required":["issueId","issues"],"additionalProperties":true,"$defs":{"@maple/ErrorIssueId":{"type":"string","pattern":"^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|[fF]{8}-[fF]{4}-[fF]{4}-[fF]{4}-[fF]{12})$","format":"uuid","title":"Error Issue ID"},"@maple/WorkflowState":{"type":"string","enum":["triage","regressed","todo","in_progress","in_review","verifying","done","cancelled","wontfix"],"title":"Workflow State"},"@maple/IsoDateTimeString":{"type":"string"},"ErrorIssueSimilarIssueEncoded":{"type":"object","properties":{"id":{"$ref":"#/$defs/@maple~1ErrorIssueId"},"serviceName":{"type":"string"},"exceptionType":{"type":"string"},"exceptionMessage":{"type":"string"},"errorLabel":{"type":"string"},"workflowState":{"$ref":"#/$defs/@maple~1WorkflowState"},"occurrenceCount":{"anyOf":[{"type":"number"},{"type":"string","enum":["Infinity","-Infinity","NaN"]}]},"lastSeenAt":{"$ref":"#/$defs/@maple~1IsoDateTimeString"},"similarity":{"anyOf":[{"type":"number"},{"type":"string","enum":["Infinity","-Infinity","NaN"]}]}},"required":["id","serviceName","exceptionType","exceptionMessage","errorLabel","workflowState","occurrenceCount","lastSeenAt","similarity"],"additionalProperties":true}}},"annotations":{"title":"List Similar Error Issues","readOnlyHint":true,"destructiveHint":false,"idempotentHint":true,"openWorldHint":false}}, {"name":"detach_error_fingerprint","title":"Detach Error Fingerprint","description":"Split one fingerprint off an error issue that the grouping key put there by mistake. Only fingerprints joined by the grouping key detach (source `group` in explain_error_grouping); one folded in by a merge is unmerged from the dashboard instead, and the issue's own fingerprint stays. The detached fingerprint is pinned, so its next occurrence opens an issue of its own.","inputSchema":{"type":"object","properties":{"issue_id":{"type":"string","description":"The issue holding the fingerprint, from list_error_issues: its UUID or its REST id (iss_\u2026)"},"fingerprint":{"type":"string","description":"The fingerprint to split off, from explain_error_grouping"}},"required":["issue_id","fingerprint"],"additionalProperties":false},"outputSchema":{"type":"object","properties":{"id":{"type":"string"},"detachedFingerprintHash":{"type":"string"},"fingerprintHashes":{"type":"array","items":{"type":"string"}},"occurrenceCount":{"anyOf":[{"type":"number"},{"type":"string","enum":["Infinity","-Infinity","NaN"]}]},"workflowState":{"type":"string"},"serviceName":{"type":"string"}},"required":["id","detachedFingerprintHash","fingerprintHashes","occurrenceCount","workflowState","serviceName"],"additionalProperties":true},"annotations":{"title":"Detach Error Fingerprint","readOnlyHint":false,"destructiveHint":false,"idempotentHint":false,"openWorldHint":false}}, {"name":"claim_error_issue","title":"Claim Error Issue","description":"Take a lease on an error issue so other agents do not duplicate the work. Issues in `triage`, `regressed` or `todo` move to `in_progress` on claim. The lease renews whenever you act on the issue (transition it, comment, set its severity, propose a fix) and ends when the issue reaches `done` or `cancelled` or you call release_error_issue. Claiming an issue another agent holds fails.","inputSchema":{"type":"object","properties":{"issue_id":{"type":"string","description":"The error issue ID from list_error_issues (a fingerprint from find_errors is not an issue id): its UUID or its REST id (iss_\u2026)"},"lease_duration_seconds":{"type":"number","description":"How long the lease lasts without activity, 60 to 7200 seconds (default 1800)"}},"required":["issue_id"],"additionalProperties":false},"outputSchema":{"type":"object","properties":{"id":{"type":"string"},"workflowState":{"type":"string"},"leaseHolderActorId":{"type":"string"},"leaseExpiresAt":{"type":"string"},"claimedAt":{"type":"string"},"holder":{"type":"string"}},"required":["id","workflowState","leaseHolderActorId","leaseExpiresAt","claimedAt","holder"],"additionalProperties":true},"annotations":{"title":"Claim Error Issue","readOnlyHint":false,"destructiveHint":false,"idempotentHint":false,"openWorldHint":false}}, diff --git a/apps/ai/src/mcp/tools/error-grouping.ts b/apps/ai/src/mcp/tools/error-grouping.ts index a24cda1e22..82d30dae91 100644 --- a/apps/ai/src/mcp/tools/error-grouping.ts +++ b/apps/ai/src/mcp/tools/error-grouping.ts @@ -37,6 +37,10 @@ export const describeRule = (fingerprint: ErrorIssueFingerprintGrouping): string return `type-function: same type, first named function ${Option.getOrElse(Arr.head(fingerprint.frames), () => "(unknown)")}` case "frames": return "frames: generic error type, keyed on these frames and the message" + case "source-mapped": + return "source-mapped: keyed on the original files and functions its source maps name, so a new release keeps the key" + case "source-mapped-function": + return `source-mapped-function: same type, first function its source maps name ${Option.getOrElse(Arr.head(fingerprint.frames), () => "(unknown)")}, so a new release keeps the key` } } diff --git a/apps/alerting/src/scheduled.ts b/apps/alerting/src/scheduled.ts index d8cc449600..d263070c47 100644 --- a/apps/alerting/src/scheduled.ts +++ b/apps/alerting/src/scheduled.ts @@ -62,7 +62,16 @@ import { import { layerMapleDbConnection } from "@maple/backend/platform/pg-connection-source" import { summarizeCause } from "@maple/backend/platform/describe-cause" import { withPgConnectionScope } from "@maple/backend/platform/pg-connection-scope" -import { EmailSender, type EmailSenderClient } from "@maple/backend/platform/bindings" +import { + EmailSender, + type EmailSenderClient, + type ObjectStore, + SourceMapReadBucket, +} from "@maple/backend/platform/bindings" +import { + StackSymbolicator, + type StackSymbolicatorApi, +} from "@maple/backend/services/sourcemaps/StackSymbolicator" import { type ChatSessionNamespace, chatSessionsLayerIfBound } from "@maple/backend/platform/chat-sessions" import { envPorts } from "@maple/backend/platform/env-ports" import { Cause, Clock, Effect, Layer, Option, Array as Arr, Record as Rec } from "effect" @@ -86,6 +95,33 @@ const statusPagesLayerIfBound = (bindings: Option.Option) => ), }) +/** + * The symbolicator over the read-only source map bucket, built once per isolate by the shell + * (`worker.ts`) so its caches outlive a tick. Its database holds only the connection string; + * each execute uses the running lane's connection scope. + */ +export const makeStackSymbolicator = ( + env: AlertingWorkerEnv, + bucket: ObjectStore, +): Effect.Effect => + Effect.service(StackSymbolicator).pipe( + // oxlint-disable-next-line effecttsgo/strict-effect-provide + Effect.provide( + StackSymbolicator.layer.pipe( + Layer.provide(Layer.succeed(SourceMapReadBucket, bucket)), + Layer.provide(DatabasePgLive), + Layer.provide(layerMapleDbConnection(env)), + ), + ), + ) + +/** Source-mapped grouping keys, only where the shell bound the source map bucket. */ +const stackSymbolicatorIfBound = (symbolicator: Option.Option) => + Option.match(symbolicator, { + onNone: () => Layer.empty, + onSome: (api) => Layer.succeed(StackSymbolicator, api), + }) + /** The secrets the ticks' services read. Unbound here, a secret reads as absent (`resources/env.ts`). */ const TickSecretsLive = Layer.mergeAll( ApnsPrivateKey.layer, @@ -114,6 +150,7 @@ export const layerTick = ( email: Option.Option = Option.none(), chatSessions?: ChatSessionNamespace, statusPages: Option.Option = Option.none(), + symbolicator: Option.Option = Option.none(), ) => Layer.mergeAll( AlertsService.layer, @@ -139,7 +176,7 @@ export const layerTick = ( DigestService.layer, WebAnalyticsDigestService.layer, FirstDataSweepService.layer, - ErrorsService.layer, + ErrorsService.layer.pipe(Layer.provide(stackSymbolicatorIfBound(symbolicator))), FixVerificationTickService.layer, EscalationService.layer, ServiceMapRollupService.layer, @@ -807,10 +844,11 @@ export const runScheduled = ( email: Option.Option, chatSessions: ChatSessionNamespace, statusPages: Option.Option, + symbolicator: Option.Option = Option.none(), ) => withPgConnectionScope(selectLaneProgram(cron, lane, scheduledTicks)).pipe( // One lane is one application run: the layer is built here and released // with it, as the async entry's ManagedRuntime was. // oxlint-disable-next-line effecttsgo/strict-effect-provide - Effect.provide(layerTick(env, email, chatSessions, statusPages)), + Effect.provide(layerTick(env, email, chatSessions, statusPages, symbolicator)), ) diff --git a/apps/alerting/src/worker.ts b/apps/alerting/src/worker.ts index a612a392ca..e13a5c9b4d 100644 --- a/apps/alerting/src/worker.ts +++ b/apps/alerting/src/worker.ts @@ -10,6 +10,7 @@ import { mapleDbEnv, MapleStack, mapleWorkerProps, + SourceMapsBucket, StatusSnapshotsBucket, StatusSnapshotsKv, } from "@maple/infra/cloudflare" @@ -20,6 +21,8 @@ import { dischargeRuntimeContext, workerEnvLayer } from "@maple/infra/worker-run import { WorkerTelemetry } from "@maple/infra/worker-telemetry" import { bindChatSessions } from "@maple/backend/platform/chat-sessions" import { bindEmailSender } from "@maple/backend/platform/email-sender" +import { type ObjectStore, ObjectStoreError } from "@maple/backend/platform/bindings" +import type { StackSymbolicatorApi } from "@maple/backend/services/sourcemaps/StackSymbolicator" import * as Cloudflare from "@alchemy.run/cloudflare" import { Cause, Config, Effect, Option, Ref } from "effect" import { FetchHttpClient, HttpClient, HttpServerResponse } from "effect/http" @@ -91,6 +94,17 @@ const cronGateFor = (env: Record) => Effect.provide(workerEnvLayer(env)), ) +/** The read side of an R2 bucket as the backend's `ObjectStore` port. */ +const readOnlyObjectStore = (client: Cloudflare.R2.ReadBucketClient): ObjectStore => ({ + getBytes: (key) => + dischargeRuntimeContext(client.get(key)).pipe( + Effect.flatMap((object) => + object === null ? Effect.succeed(Option.none()) : Effect.asSome(object.bytes()), + ), + Effect.mapError((error) => new ObjectStoreError({ message: error.message, cause: error.cause })), + ), +}) + export default class Alerting extends Cloudflare.Worker()( "alerting", props, @@ -106,6 +120,12 @@ export default class Alerting extends Cloudflare.Worker()( // Where published status pages live; ticks publish snapshots and import break-glass posts. const statusKv = yield* Cloudflare.KV.ReadWriteNamespace(StatusSnapshotsKv) const statusBucket = yield* Cloudflare.R2.ReadWriteBucket(StatusSnapshotsBucket) + // Uploaded source maps, read-only: the errors tick keys minified stacks on their mapped frames. + const sourceMapsClient = yield* Cloudflare.R2.ReadBucket(SourceMapsBucket) + const sourceMaps = readOnlyObjectStore(sourceMapsClient) + // The symbolicator, built on the first fire (it needs the env) and kept for the isolate, so + // its parsed-map and lookup caches outlive one tick. + const symbolicator = yield* Ref.make(Option.none()) // Once per isolate, not once per fire. const loggedNonProdSkip = yield* Ref.make(false) // Once per isolate too: an isolate never changes data center. @@ -116,11 +136,25 @@ export default class Alerting extends Cloudflare.Worker()( const runTick = (cron: string, lane: string, env: Record) => Effect.gen(function* () { - const { runScheduled } = yield* scheduled + const { runScheduled, makeStackSymbolicator } = yield* scheduled + const built = yield* Ref.get(symbolicator) + const stacks = Option.isSome(built) + ? built.value + : yield* makeStackSymbolicator(env, sourceMaps).pipe( + Effect.tap((made) => Ref.set(symbolicator, Option.some(made))), + ) const [kv, bucket] = yield* dischargeRuntimeContext( Effect.all([statusKv.raw, statusBucket.raw]), ) - yield* runScheduled(cron, lane, env, email, chatSessions, Option.some({ kv, bucket })) + yield* runScheduled( + cron, + lane, + env, + email, + chatSessions, + Option.some({ kv, bucket }), + Option.some(stacks), + ) }).pipe( // Interrupts are isolate teardown, not a failed run. Effect.catchCause((cause) => @@ -237,6 +271,7 @@ export default class Alerting extends Cloudflare.Worker()( Cloudflare.Email.SendBinding, Cloudflare.KV.ReadWriteNamespaceBinding, Cloudflare.R2.ReadWriteBucketBinding, + Cloudflare.R2.ReadBucketBinding, Cloudflare.Workers.CronEventSourceLive, FetchHttpClient.layer, WorkerTelemetry({ diff --git a/apps/api/src/routes/v2/error-issues.http.ts b/apps/api/src/routes/v2/error-issues.http.ts index 1d4388f8da..aa4d52f15e 100644 --- a/apps/api/src/routes/v2/error-issues.http.ts +++ b/apps/api/src/routes/v2/error-issues.http.ts @@ -114,6 +114,7 @@ export const toV2IssueDetail = (detail: ErrorIssueDetailResponse): V2ErrorIssueD incidents: Arr.map(detail.incidents, toV2Incident), environments: Arr.map(detail.environments, (env) => ({ name: env.name, count: env.count })), latest_stacktrace: detail.latestStacktrace, + latest_stack: detail.latestStack, }) const decodeCursor = ( diff --git a/apps/api/src/routes/v2/phase1-resources.http.test.ts b/apps/api/src/routes/v2/phase1-resources.http.test.ts index d97749e1b1..e5151ad87e 100644 --- a/apps/api/src/routes/v2/phase1-resources.http.test.ts +++ b/apps/api/src/routes/v2/phase1-resources.http.test.ts @@ -355,6 +355,7 @@ const errorIssueDetailFixture = new ErrorIssueDetailResponse({ incidents: [errorIncidentFixture], environments: [new ErrorIssueEnvironment({ name: "production", count: 12 })], latestStacktrace: null, + latestStack: null, }) const die = () => Effect.die(new Error("not exercised in this test harness")) diff --git a/apps/api/src/routes/v2/source-maps.http.test.ts b/apps/api/src/routes/v2/source-maps.http.test.ts new file mode 100644 index 0000000000..d9f4bb3997 --- /dev/null +++ b/apps/api/src/routes/v2/source-maps.http.test.ts @@ -0,0 +1,248 @@ +import { afterEach, describe, expect, it } from "@effect/vitest" +import { ConfigProvider, Context, Effect, Layer, ManagedRuntime, Schema } from "effect" +import { HttpRouter } from "effect/http" +import { HttpApi, HttpApiBuilder } from "effect/http-api" +import { OrgId, UserId } from "@maple/domain/http" +import { MapleApiV2 } from "@maple/domain/http/v2" +import { inMemoryObjectStore, sourceMapBucketLayer } from "@maple/backend/platform/bindings" +import { Env } from "@maple/backend/platform/Env" +import { ApiAuthorizationV2Live } from "@maple/backend/services/auth/ApiAuthorizationV2Live" +import { AuditLogService } from "@maple/backend/services/audit/AuditLogService" +import { ApiKeysService } from "@maple/backend/services/org/ApiKeysService" +import { AuthService } from "@maple/backend/services/auth/AuthService" +import { SourceMapService } from "@maple/backend/services/sourcemaps/SourceMapService" +import { cleanupTestDbs, createTestDb, type TestDb } from "@maple/backend/testing/test-pglite" +import { V2TransportErrorBoundaryLive } from "./error-envelope" +import { HttpV2SourceMapsLive } from "./source-maps.http" +import { ApiV2RateLimiterAllowAllLayer, Phase1ResourceStubsLayer } from "./v2-test-support" + +const createdDbs: TestDb[] = [] +afterEach(() => cleanupTestDbs(createdDbs)) + +const testConfig = ConfigProvider.layer( + ConfigProvider.fromUnknown({ + PORT: "3482", + MCP_PORT: "3483", + TINYBIRD_HOST: "https://api.tinybird.co", + TINYBIRD_TOKEN: "test-token", + MAPLE_AUTH_MODE: "self_hosted", + MAPLE_ROOT_PASSWORD: "test-root-password", + MAPLE_DEFAULT_ORG_ID: "default", + MAPLE_INGEST_KEY_ENCRYPTION_KEY: Buffer.alloc(32, 1).toString("base64"), + MAPLE_INGEST_KEY_LOOKUP_HMAC_KEY: "maple-test-lookup-secret", + INTERNAL_SERVICE_TOKEN: "test-internal-token", + }), +) + +const ORG = Schema.decodeSync(OrgId)("org_source_maps_e2e") +const USER = Schema.decodeSync(UserId)("user_source_maps_e2e") +const DEBUG_ID = "6c5e2b1a-1f2e-4d3c-8b7a-0123456789ab" + +const makeHarness = () => { + const objects = new Map() + const servicesLive = Layer.mergeAll(ApiKeysService.layer, AuthService.layer, SourceMapService.layer).pipe( + Layer.provideMerge( + Layer.mergeAll( + Env.layer.pipe(Layer.provide(testConfig)), + createTestDb(createdDbs).layer, + sourceMapBucketLayer(inMemoryObjectStore(objects)), + ), + ), + ) + const routes = HttpApiBuilder.layer(HttpApi.make("MapleApiV2").add(MapleApiV2.groups.sourceMaps)).pipe( + Layer.provide(HttpV2SourceMapsLive), + Layer.provide(V2TransportErrorBoundaryLive), + Layer.provide(Phase1ResourceStubsLayer), + Layer.provideMerge(ApiAuthorizationV2Live), + Layer.provideMerge(AuditLogService.layerMemory), + Layer.provideMerge(ApiV2RateLimiterAllowAllLayer), + Layer.provideMerge(servicesLive), + ) + const { handler, dispose } = HttpRouter.toWebHandler(routes, { disableLogger: true }) + const runtime = ManagedRuntime.make(servicesLive) + + const createKey = (options: { scopes?: ReadonlyArray; roles?: ReadonlyArray } = {}) => + runtime.runPromise( + Effect.gen(function* () { + const keys = yield* ApiKeysService + return yield* keys.create(ORG, USER, { + name: "source-maps-test", + scopes: options.scopes, + ...(options.roles === undefined + ? undefined + : { + metadataJson: { + source: "maple_cli", + roles: options.roles, + deviceName: "laptop", + }, + }), + }) + }), + ) + + const request = async ( + method: string, + path: string, + token: string, + body?: { + readonly bytes: Uint8Array + readonly contentType: string + readonly contentLength?: number + }, + ) => { + const response = await handler( + new Request(`http://maple.test${path}`, { + method, + headers: { + authorization: `Bearer ${token}`, + ...(body === undefined ? undefined : { "content-type": body.contentType }), + ...(body?.contentLength === undefined + ? undefined + : { "content-length": String(body.contentLength) }), + }, + body: body?.bytes, + }), + Context.empty(), + ) + const text = await response.text() + return { status: response.status, body: text.length > 0 ? JSON.parse(text) : null } + } + + return { + objects, + createKey, + request, + dispose: async () => { + await dispose() + await runtime.dispose() + }, + } +} + +const mapBody = (contentType = "application/octet-stream") => ({ + bytes: new TextEncoder().encode( + JSON.stringify({ + version: 3, + sources: ["src/a.ts"], + sourcesContent: ["x"], + names: [], + mappings: "AAAA", + }), + ), + contentType, +}) + +describe("v2 source_maps over HTTP", () => { + it("uploads raw bytes, lists and deletes with the public wire shape", async () => { + const harness = makeHarness() + const key = await harness.createKey({ scopes: ["source_maps:write"] }) + + const uploaded = await harness.request( + "POST", + `/v2/source_maps?minified_path=/assets/index-Bx81.js&debug_id=${DEBUG_ID}`, + key.secret, + mapBody(), + ) + expect(uploaded.status).toBe(200) + expect(uploaded.body).toMatchObject({ + object: "source_map", + debug_id: DEBUG_ID, + service: null, + version: null, + minified_path: "assets/index-Bx81.js", + has_sources_content: true, + last_used_at: null, + }) + expect(uploaded.body.id).toMatch(/^smap_/) + expect(uploaded.body.size_bytes).toBe(mapBody().bytes.byteLength) + expect(harness.objects.size).toBe(1) + + const asJson = await harness.request( + "POST", + "/v2/source_maps?minified_path=assets/b.js&service=web&version=1.0.0", + key.secret, + mapBody("application/json"), + ) + expect(asJson.status).toBe(200) + + const listed = await harness.request("GET", "/v2/source_maps?service=web&limit=1", key.secret) + expect(listed.status).toBe(200) + expect(listed.body).toMatchObject({ object: "list", has_more: false, next_cursor: null }) + expect(listed.body.data.map((row: { id: string }) => row.id)).toEqual([asJson.body.id]) + + const deleted = await harness.request("DELETE", `/v2/source_maps/${uploaded.body.id}`, key.secret) + expect(deleted.status).toBe(200) + expect(deleted.body.id).toBe(uploaded.body.id) + expect(harness.objects.size).toBe(1) + + const missing = await harness.request("DELETE", `/v2/source_maps/${uploaded.body.id}`, key.secret) + expect(missing.status).toBe(404) + expect(missing.body.error._tag).toBe("@maple/http/sourcemaps/SourceMapNotFoundError") + await harness.dispose() + }) + + it("refuses a body over 10 MiB by its Content-Length, and one that runs over while read", async () => { + const harness = makeHarness() + const key = await harness.createKey({ scopes: ["source_maps:write"] }) + const path = `/v2/source_maps?minified_path=assets/a.js&debug_id=${DEBUG_ID}` + + // The header alone decides: the small body behind it is never read. + const declared = await harness.request("POST", path, key.secret, { + ...mapBody(), + contentLength: 10 * 1024 * 1024 + 1, + }) + expect(declared.status).toBe(413) + expect(declared.body.error._tag).toBe("@maple/http/sourcemaps/SourceMapTooLargeError") + // The size is in the answer, so a CI upload learns which map and by how much. + expect(declared.body.error.message).toContain(String(10 * 1024 * 1024 + 1)) + + const oversized = await harness.request("POST", path, key.secret, { + bytes: new Uint8Array(10 * 1024 * 1024 + 1), + contentType: "application/octet-stream", + }) + expect(oversized.status).toBe(413) + expect(harness.objects.size).toBe(0) + await harness.dispose() + }) + + it("rejects an upload that cannot be matched, a read-only key and a member", async () => { + const harness = makeHarness() + const writer = await harness.createKey() + + const unmatched = await harness.request( + "POST", + "/v2/source_maps?minified_path=assets/a.js&service=web", + writer.secret, + mapBody(), + ) + expect(unmatched.status).toBe(400) + expect(unmatched.body.error).toMatchObject({ + _tag: "@maple/http/sourcemaps/SourceMapInvalidError", + param: "debug_id", + }) + + const reader = await harness.createKey({ scopes: ["source_maps:read"] }) + const readOnly = await harness.request( + "POST", + `/v2/source_maps?minified_path=assets/a.js&debug_id=${DEBUG_ID}`, + reader.secret, + mapBody(), + ) + expect(readOnly.status).toBe(403) + expect((await harness.request("GET", "/v2/source_maps", reader.secret)).status).toBe(200) + + const member = await harness.createKey({ roles: ["org:member"] }) + const memberUpload = await harness.request( + "POST", + `/v2/source_maps?minified_path=assets/a.js&debug_id=${DEBUG_ID}`, + member.secret, + mapBody(), + ) + expect(memberUpload.status).toBe(403) + expect(memberUpload.body.error._tag).toBe("@maple/http/v2/InsufficientPermissionsError") + expect((await harness.request("GET", "/v2/source_maps", member.secret)).status).toBe(200) + expect(harness.objects.size).toBe(0) + await harness.dispose() + }) +}) diff --git a/apps/api/src/routes/v2/source-maps.http.ts b/apps/api/src/routes/v2/source-maps.http.ts new file mode 100644 index 0000000000..8cd0c3d8a8 --- /dev/null +++ b/apps/api/src/routes/v2/source-maps.http.ts @@ -0,0 +1,130 @@ +import { HttpApiBuilder } from "effect/http-api" +import type { HttpServerRequest } from "effect/http" +import { HttpIncomingMessage } from "effect/http" +import { + CurrentTenant, + SOURCE_MAP_MAX_BYTES, + SourceMapInvalidError, + SourceMapTooLargeError, +} from "@maple/domain/http" +import { isoTimestamp, isoTimestampOrNull, MapleApiV2, paginateOffsetQuery } from "@maple/domain/http/v2" +import { V2InsufficientPermissions, type V2SourceMap } from "@maple/domain/http/v2" +import type { SourceMapFileRow } from "@maple/db/tables" +import { Array as Arr, ByteSize, Effect, Option } from "effect" +import * as Policy from "@maple/domain/policy" +import { recordHttpAudit } from "@maple/backend/services/audit/AuditLogService" +import { SourceMapService } from "@maple/backend/services/sourcemaps/SourceMapService" + +const toV2SourceMap = (row: SourceMapFileRow): V2SourceMap => ({ + object: "source_map", + id: row.id, + debug_id: row.debugId, + service: row.serviceName, + version: row.version, + minified_path: row.minifiedPath, + size_bytes: row.sizeBytes, + has_sources_content: row.hasSourcesContent, + created_at: isoTimestamp(row.createdAt), + last_used_at: isoTimestampOrNull(row.lastUsedAt), +}) + +// Uploads decide what every member sees in stack traces, so they take the role that manages +// ingest keys; listing stays open to members. +const requireUpload = (tenant: CurrentTenant.TenantSchema) => + Policy.check(tenant.roles, "source_maps:upload", (denial) => + V2InsufficientPermissions.make(denial.message), + ) + +const tooLarge = (sizeBytes: number) => + new SourceMapTooLargeError({ + message: `Source map is ${sizeBytes} bytes; the limit is ${SOURCE_MAP_MAX_BYTES} (10 MiB), the largest map Maple can symbolicate with.`, + sizeBytes, + }) + +/** + * The body, refused by its `Content-Length` before any of it is read, and cut off at the limit + * while reading when the header is absent or wrong. + */ +const readLimitedBody = ( + request: HttpServerRequest.HttpServerRequest, +): Effect.Effect => + Effect.gen(function* () { + const declared = Option.filter( + Option.fromNullishOr(request.headers["content-length"]).pipe(Option.map(Number)), + Number.isFinite, + ) + if (Option.isSome(declared) && declared.value > SOURCE_MAP_MAX_BYTES) { + return yield* tooLarge(declared.value) + } + const buffer = yield* request.arrayBuffer.pipe( + Effect.provideService(HttpIncomingMessage.MaxBodySize, ByteSize.bytes(SOURCE_MAP_MAX_BYTES)), + Effect.mapError((error): SourceMapTooLargeError | SourceMapInvalidError => + error.reason._tag === "RequestParseError" && error.reason.reason === "BodyTooLarge" + ? tooLarge(SOURCE_MAP_MAX_BYTES + 1) + : new SourceMapInvalidError({ message: "The request body could not be read." }), + ), + ) + return new Uint8Array(buffer) + }) + +export const HttpV2SourceMapsLive = HttpApiBuilder.group(MapleApiV2, "sourceMaps", (handlers) => + Effect.gen(function* () { + const sourceMaps = yield* SourceMapService + + return ( + handlers + // Raw, so an oversized body is refused before it is buffered into the isolate. + .handleRaw("upload", ({ query, request }) => + Effect.gen(function* () { + const tenant = yield* CurrentTenant.Context + yield* requireUpload(tenant) + const bytes = yield* readLimitedBody(request) + const row = yield* sourceMaps.upload(tenant.orgId, { + bytes, + minifiedPath: query.minified_path, + debugId: query.debug_id, + serviceName: query.service, + version: query.version, + }) + yield* recordHttpAudit("source_map.uploaded", { + resourceId: row.id, + metadata: { + minified_path: row.minifiedPath, + ...(row.debugId === null ? undefined : { debug_id: row.debugId }), + ...(row.serviceName === null ? undefined : { service: row.serviceName }), + ...(row.version === null ? undefined : { version: row.version }), + }, + }) + return toV2SourceMap(row) + }), + ) + .handle("list", ({ query }) => + Effect.gen(function* () { + const tenant = yield* CurrentTenant.Context + const page = yield* paginateOffsetQuery(query, ({ limit, offset }) => + sourceMaps.list(tenant.orgId, { + serviceName: query.service, + version: query.version, + debugId: query.debug_id, + limit, + offset, + }), + ) + return { object: "list" as const, ...page, data: Arr.map(page.data, toV2SourceMap) } + }), + ) + .handle("delete", ({ params }) => + Effect.gen(function* () { + const tenant = yield* CurrentTenant.Context + yield* requireUpload(tenant) + const row = yield* sourceMaps.remove(tenant.orgId, params.id) + yield* recordHttpAudit("source_map.deleted", { + resourceId: row.id, + metadata: { minified_path: row.minifiedPath }, + }) + return toV2SourceMap(row) + }), + ) + ) + }), +) diff --git a/apps/api/src/runtime/http-graph.ts b/apps/api/src/runtime/http-graph.ts index 47da9a7a13..7b0edb53d6 100644 --- a/apps/api/src/runtime/http-graph.ts +++ b/apps/api/src/runtime/http-graph.ts @@ -75,6 +75,7 @@ import { HttpV2AlertRulesLive } from "@/routes/v2/alert-rules.http" import { HttpV2AnomaliesLive } from "@/routes/v2/anomalies.http" import { HttpV2ApiKeysLive } from "@/routes/v2/api-keys.http" import { HttpV2AttributeMappingsLive } from "@/routes/v2/attribute-mappings.http" +import { HttpV2SourceMapsLive } from "@/routes/v2/source-maps.http" import { HttpV2DataSourcesLive } from "@/routes/v2/data-sources.http" import { HttpV2IngestRulesLive } from "@/routes/v2/ingest-rules.http" import { HttpV2DashboardsLive } from "@/routes/v2/dashboards.http" @@ -246,6 +247,7 @@ const ApiV2Routes = HttpApiBuilder.layer(MapleApiV2).pipe( HttpV2AwsIntegrationsLive, HttpV2ErrorIssuesLive, HttpV2AttributeMappingsLive, + HttpV2SourceMapsLive, HttpV2DataSourcesLive, HttpV2IngestRulesLive, HttpV2AuditLogLive, diff --git a/apps/api/src/runtime/service-graph.ts b/apps/api/src/runtime/service-graph.ts index bc9edc968a..b1084e46ec 100644 --- a/apps/api/src/runtime/service-graph.ts +++ b/apps/api/src/runtime/service-graph.ts @@ -120,6 +120,8 @@ import { GithubConnectService } from "@maple/backend/services/integrations/vcs/v import { ApiKeysService } from "@maple/backend/services/org/ApiKeysService" import { DemoService } from "@maple/backend/services/org/DemoService" import { IngestAttributeMappingService } from "@maple/backend/services/org/IngestAttributeMappingService" +import { SourceMapService } from "@maple/backend/services/sourcemaps/SourceMapService" +import { StackSymbolicator } from "@maple/backend/services/sourcemaps/StackSymbolicator" import { IngestRuleService } from "@maple/backend/services/org/IngestRuleService" import { IngestRulePreviewService } from "@maple/backend/services/org/IngestRulePreviewService" import { OnboardingChecklistService } from "@maple/backend/services/org/OnboardingChecklistService" @@ -239,6 +241,8 @@ export const HttpServicesLive = Layer.mergeAll( PlanetScaleService.layer, PlanetScaleWebhookService.layer, IngestAttributeMappingService.layer, + // Needs the `SourceMapBucket` port, which only the deployed Worker binds. + SourceMapService.layer, IngestRuleService.layer, IngestRulePreviewService.layer, AutumnClient.layer, @@ -307,9 +311,11 @@ export const HttpServicesLive = Layer.mergeAll( ErrorActorsService.layer, ErrorIssueWorkflowService.layer, ErrorIssueMergeService.layer, - ErrorGroupingService.layer, + // "Why grouped" shows the frames the key was computed from, source-mapped like the tick's. + ErrorGroupingService.layer.pipe(Layer.provide(StackSymbolicator.layer)), ErrorPolicyService.layer, - ErrorIssueReadModelsService.layer, + // Symbolicates the detail's latest stack through the org's source maps (needs `SourceMapReadBucket`). + ErrorIssueReadModelsService.layer.pipe(Layer.provide(StackSymbolicator.layer)), ErrorsService.layer, // The investigation gate's classifier, for the alert path that opens // incidents from a request. Read optionally by `maybeEnqueueTriage`. diff --git a/apps/api/src/worker/bindings.ts b/apps/api/src/worker/bindings.ts index 5622ccf8f2..a4f8ecbf14 100644 --- a/apps/api/src/worker/bindings.ts +++ b/apps/api/src/worker/bindings.ts @@ -8,10 +8,10 @@ */ import { StatusPageStore } from "@maple/backend/services/status-pages/StatusPageStore" import { StatusSnapshotsBucket, StatusSnapshotsKv } from "@maple/infra/cloudflare" -import { AuditIntakeQueue, MapleDb, ReplayBlobs } from "@maple/infra/cloudflare" +import { AuditIntakeQueue, MapleDb, ReplayBlobs, SourceMapsBucket } from "@maple/infra/cloudflare" import * as Cloudflare from "@alchemy.run/cloudflare" import { dischargeRuntimeContext } from "@maple/infra/worker-runtime" -import { Effect, Layer, Option } from "effect" +import { Array as Arr, Effect, Layer, Option } from "effect" import { ApiV2RateLimit, AuditEventsQueueProducer, @@ -36,6 +36,8 @@ import { VcsSyncQueueProducer, WorkflowStartError, type WorkflowStarter, + sourceMapBucketLayer, + type WritableObjectStore, } from "@maple/backend/platform/bindings" import { bindChatSessions, layerChatSessions } from "@maple/backend/platform/chat-sessions" import { bindEmailSender } from "@maple/backend/platform/email-sender" @@ -87,6 +89,8 @@ export const bindApiClients = Effect.gen(function* () { // Published status pages: the publish endpoint writes snapshots, page deletes clear them. statusKv: yield* Cloudflare.KV.ReadWriteNamespace(StatusSnapshotsKv), statusBucket: yield* Cloudflare.R2.ReadWriteBucket(StatusSnapshotsBucket), + // Uploaded source maps: the v2 upload writes them, symbolication reads them. + sourceMaps: yield* Cloudflare.R2.ReadWriteBucket(SourceMapsBucket), apiV2RateLimit: yield* Cloudflare.RateLimit("API_V2_RATE_LIMITER", { namespaceId: 2026071801, simple: { limit: API_V2_RATE_LIMIT_REQUESTS, period: API_V2_RATE_LIMIT_PERIOD_SECONDS }, @@ -173,6 +177,41 @@ const objectStore = (client: Cloudflare.R2.ReadBucketClient): ObjectStore => ({ ), }) +const objectStoreError = (error: { readonly message: string; readonly cause: unknown }) => + new ObjectStoreError({ message: error.message, cause: error.cause }) + +const writableObjectStore = (client: Cloudflare.R2.ReadWriteBucketClient): WritableObjectStore => ({ + ...objectStore(client), + list: ({ prefix, startAfter, limit }) => + dischargeRuntimeContext( + client.list({ prefix, limit, ...(startAfter === undefined ? undefined : { startAfter }) }), + ).pipe( + Effect.mapBoth({ + onSuccess: (page) => ({ + objects: Arr.map(page.objects, (object) => ({ + key: object.key, + uploadedAt: object.uploaded.getTime(), + })), + truncated: page.truncated, + }), + onFailure: objectStoreError, + }), + ), + put: (key, bytes, contentType) => + dischargeRuntimeContext(client.put(key, bytes, { httpMetadata: { contentType } })).pipe( + Effect.asVoid, + Effect.mapError((error) => new ObjectStoreError({ message: error.message, cause: error.cause })), + ), + delete: (keys) => + keys.length === 0 + ? Effect.void + : dischargeRuntimeContext(client.delete([...keys])).pipe( + Effect.mapError( + (error) => new ObjectStoreError({ message: error.message, cause: error.cause }), + ), + ), +}) + /** * Alchemy's `create` dies when the binding rejects; recovered here into the * port's typed channel, so the caller can release the run it claimed. @@ -220,6 +259,7 @@ export const apiPorts = ( Layer.succeed(DataSourceDevelopmentCallLimit, limiter(clients.dataSourceDevelopmentCallLimit)), Layer.succeed(DataSourceSqlQueryLimit, limiter(clients.dataSourceSqlQueryLimit)), Layer.succeed(ReplayBlobBucket, objectStore(clients.replayBlobs)), + sourceMapBucketLayer(writableObjectStore(clients.sourceMaps)), Layer.unwrap( dischargeRuntimeContext(Effect.all([clients.statusKv.raw, clients.statusBucket.raw])).pipe( Effect.map(([kv, bucket]) => StatusPageStore.fromBindings(kv, bucket)), diff --git a/apps/api/src/worker/crons.ts b/apps/api/src/worker/crons.ts index b83514c6f8..294ec40741 100644 --- a/apps/api/src/worker/crons.ts +++ b/apps/api/src/worker/crons.ts @@ -3,7 +3,8 @@ * every 12h — VCS sync backstop, enqueues a refresh per installation * hourly — scrape_target_checks retention (was inline on the * scrape-results write path; a busy target writes ~75k - * rows/day, so the 10k cap binds within hours) + * rows/day, so the 10k cap binds within hours), PlanetScale + * event retention, and source maps unused for 90 days */ import * as Cloudflare from "@alchemy.run/cloudflare" import { Effect, Layer } from "effect" @@ -28,25 +29,33 @@ export const registerCrons = (ports: ApiPortsLayer) => ) yield* Cloudflare.Workers.cron(SCRAPE_RETENTION_CRON, () => Effect.gen(function* () { - const [{ vcsSyncTelemetry }, { runScrapeCheckRetention }, { runPlanetScaleEventRetention }] = - yield* Effect.all([ - vcsSyncModule, - Effect.promise( - () => import("@maple/backend/services/integrations/scrape-check-retention"), - ), - Effect.promise( - () => import("@maple/backend/services/integrations/planetscale-event-retention"), - ), - ]) - // Both sweeps ride this one cron, sequentially: they share the tick's + const [ + { vcsSyncTelemetry }, + { runScrapeCheckRetention }, + { runPlanetScaleEventRetention }, + { runSourceMapRetention }, + ] = yield* Effect.all([ + vcsSyncModule, + Effect.promise( + () => import("@maple/backend/services/integrations/scrape-check-retention"), + ), + Effect.promise( + () => import("@maple/backend/services/integrations/planetscale-event-retention"), + ), + Effect.promise(() => import("@maple/backend/services/sourcemaps/SourceMapService")), + ]) + // The sweeps ride this one cron, sequentially: they share the tick's // one Postgres socket, so running them concurrently would only queue. A failed // sweep does not skip the next. - // The jobs talk only to Postgres, so the layer is the database alone. + // The jobs talk to Postgres, and the source map sweep to its bucket from `ports`. return yield* runEvent( - Effect.all([runScrapeCheckRetention, runPlanetScaleEventRetention], { - mode: "result", - discard: true, - }), + Effect.all( + [runScrapeCheckRetention, runPlanetScaleEventRetention, runSourceMapRetention], + { + mode: "result", + discard: true, + }, + ), DatabasePgLive.pipe(Layer.provideMerge(vcsSyncTelemetry), Layer.provideMerge(ports)), ) }).pipe(settleFire(SCRAPE_RETENTION_CRON)), diff --git a/apps/api/test/offline-http-ports.ts b/apps/api/test/offline-http-ports.ts index 453ddd5c84..704ef1533f 100644 --- a/apps/api/test/offline-http-ports.ts +++ b/apps/api/test/offline-http-ports.ts @@ -20,6 +20,7 @@ import { SchemaApplyWorkflow, SelfHostedLoginRateLimit, ShareLinkRateLimit, + sourceMapBucketLayer, VcsBackfillQueueProducer, VcsSyncQueueProducer, } from "@maple/backend/platform/bindings" @@ -42,6 +43,7 @@ export const offlinePorts = Layer.mergeAll( Layer.succeed(DataSourceDevelopmentCallLimit, limiter), Layer.succeed(DataSourceSqlQueryLimit, limiter), Layer.succeed(ReplayBlobBucket, { getBytes: rejectIO }), + sourceMapBucketLayer({ getBytes: rejectIO, put: rejectIO, delete: rejectIO, list: rejectIO }), StatusPageStore.inMemory, Layer.succeed(MapleDbConnection, Option.none()), Layer.succeed(EmailSender, Option.none()), diff --git a/apps/cli/package.json b/apps/cli/package.json index 9f172b3028..880cb5a1a5 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -10,7 +10,7 @@ "start": "bun run src/bin.ts", "bench:ingest": "bun bench/ingest-http.ts", "bench:ingest:chdb": "bun bench/ingest-chdb.ts", - "test": "bun test --max-concurrency=1 test/*.test.ts src/core/*.test.ts", + "test": "bun test --max-concurrency=1 test/*.test.ts src/core/*.test.ts src/commands/*.test.ts", "typecheck": "tsrs --noEmit" }, "dependencies": { @@ -21,6 +21,7 @@ "@maple/local-server": "workspace:*", "@maple/promql": "workspace:*", "@maple/query-engine": "workspace:*", + "@maple/sourcemaps": "workspace:*", "effect": "catalog:effect" }, "devDependencies": { diff --git a/apps/cli/src/cli.ts b/apps/cli/src/cli.ts index 4662949ca2..c962a533e5 100644 --- a/apps/cli/src/cli.ts +++ b/apps/cli/src/cli.ts @@ -19,6 +19,7 @@ import { update } from "./commands/update" import { changelog } from "./commands/changelog" import { onboarding } from "./commands/onboarding" import { users, user, events } from "./commands/users" +import { sourcemaps } from "./commands/sourcemaps" import { OutputFormatSetting } from "./lib/output" // One CLI, two backends. Local mode runs the query-engine helpers against the @@ -91,5 +92,6 @@ export const cli = Command.make("maple").pipe( post, put, patch, + sourcemaps, ]), ) diff --git a/apps/cli/src/commands/sourcemaps.test.ts b/apps/cli/src/commands/sourcemaps.test.ts new file mode 100644 index 0000000000..521c9134f8 --- /dev/null +++ b/apps/cli/src/commands/sourcemaps.test.ts @@ -0,0 +1,67 @@ +import { afterEach, beforeEach, describe, expect, test } from "bun:test" +import * as BunServices from "@effect/platform-bun/BunServices" +import { Effect, Option, String as Str } from "effect" +import { execFileSync } from "node:child_process" +import { mkdtempSync, rmSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { SourceMapUploadError } from "../core/sourcemaps-upload" +import { checkUploadOutcomes, gitHead } from "./sourcemaps" + +let dir = "" +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), "maple-sourcemaps-cmd-")) +}) +afterEach(() => rmSync(dir, { recursive: true, force: true })) + +const git = (...args: ReadonlyArray) => + Str.trim(execFileSync("git", [...args], { cwd: dir, encoding: "utf8" })) + +describe("gitHead", () => { + test("reads the commit of the build directory's checkout, not the shell's", async () => { + git("init", "-q") + writeFileSync(join(dir, "a.txt"), "a") + git("add", "a.txt") + git("-c", "user.name=t", "-c", "user.email=t@example.com", "commit", "-q", "-m", "init") + const buildHead = git("rev-parse", "HEAD") + const shellHead = Str.trim(execFileSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" })) + + const head = await Effect.runPromise(Effect.provide(gitHead(dir), BunServices.layer)) + + expect(Option.getOrNull(head)).toBe(buildHead) + expect(buildHead).not.toBe(shellHead) + }) + + test("is none outside a git work tree", async () => { + const head = await Effect.runPromise(Effect.provide(gitHead(dir), BunServices.layer)) + expect(Option.isNone(head)).toBe(true) + }) +}) + +describe("checkUploadOutcomes", () => { + const skipped = { _tag: "skipped", minifiedPath: "a.js", reason: "no debug id" } as const + const uploaded = { + _tag: "uploaded", + minifiedPath: "b.js", + debugId: Option.none(), + sizeBytes: 1, + id: Option.none(), + } as const + + test("fails when every map was skipped, so CI does not go on without maps", async () => { + const error = await Effect.runPromise(Effect.flip(checkUploadOutcomes("dist", [skipped, skipped]))) + expect(error._tag).toBe("@maple/cli/UsageError") + expect(error.message).toBe("no source maps were uploaded; every matching map was skipped") + }) + + test("passes when at least one map went up, and reports a failed one", async () => { + await Effect.runPromise(checkUploadOutcomes("dist", [skipped, uploaded])) + const failed = { + _tag: "failed", + minifiedPath: "c.js", + error: new SourceMapUploadError({ message: "HTTP 400: bad", minifiedPath: "c.js", status: 400 }), + } as const + const error = await Effect.runPromise(Effect.flip(checkUploadOutcomes("dist", [uploaded, failed]))) + expect(error._tag).not.toBe("@maple/cli/UsageError") + }) +}) diff --git a/apps/cli/src/commands/sourcemaps.ts b/apps/cli/src/commands/sourcemaps.ts new file mode 100644 index 0000000000..7c247567f3 --- /dev/null +++ b/apps/cli/src/commands/sourcemaps.ts @@ -0,0 +1,186 @@ +import * as Argument from "effect/cli/Argument" +import * as Command from "effect/cli/Command" +import * as Flag from "effect/cli/Flag" +import { Array as Arr, Console, Effect, Option, Redacted, Stream, String as Str } from "effect" +import * as ChildProcess from "effect/process/ChildProcess" +import { ChildProcessSpawner } from "effect/process/ChildProcessSpawner" +import { MapleConfig } from "../core/config" +import { injectDirectory, type InjectResult } from "../core/sourcemaps" +import { uploadDirectory, type UploadOutcome } from "../core/sourcemaps-upload" +import { ApiResponseError, ApiTransportError } from "./api" +import { CliUsageError } from "../lib/errors" + +const dirArg = Argument.Directory("dir", { mustExist: true }).pipe( + Argument.withDescription("Build output directory, e.g. dist"), +) + +const inject = Command.make("inject", { + dir: dirArg, + dryRun: Flag.Boolean("dry-run").pipe( + Flag.withDescription("Report what would change without writing any file"), + Flag.withDefault(false), + ), +}).pipe( + Command.withDescription( + "Add a debug id to every built JS file that has a source map, and to its map. Run after the build, before deploying and uploading; re-running changes nothing", + ), + Command.withHandler(({ dir, dryRun }) => + Effect.gen(function* () { + const results = yield* injectDirectory(dir, { dryRun }) + const verb = dryRun ? "would inject" : "injected" + const mapOf = (r: InjectResult) => Option.getOrElse(r.mapPath, () => "") + yield* Effect.forEach(results, (r) => { + switch (r.status) { + case "invalid_map": + return Console.error( + `warning: skipped ${r.file}: its source map ${mapOf(r)} is not a version 3 JSON object`, + ) + case "unsafe_map": + return Console.error( + `warning: skipped ${r.file}: its source map ${mapOf(r)} is outside ${dir}`, + ) + case "injected": + return Console.log(`${verb} ${r.file} (${Option.getOrElse(r.debugId, () => "")})`) + default: + return Effect.void + } + }) + const count = (status: string) => Arr.filter(results, (r) => r.status === status).length + yield* Console.log( + `${dryRun ? "Would inject" : "Injected"} ${count("injected")} file(s); skipped ${count("already_injected")} already injected, ${count("no_map")} without a source map` + + (count("invalid_map") > 0 ? `, ${count("invalid_map")} with an unreadable map` : "") + + (count("unsafe_map") > 0 ? `, ${count("unsafe_map")} with a map outside ${dir}` : ""), + ) + }), + ), +) + +/** The commit checked out where `dir` is, when it is inside a git work tree. */ +export const gitHead = (dir: string) => + Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner + const handle = yield* spawner.spawn( + ChildProcess.make("git", ["rev-parse", "HEAD"], { + cwd: dir, + stdin: "ignore", + stdout: "pipe", + stderr: "ignore", + }), + ) + const [exitCode, stdout] = yield* Effect.all( + [handle.exitCode, Stream.mkString(Stream.decodeText(handle.stdout))], + { concurrency: "unbounded" }, + ) + const sha = Str.trim(stdout) + return exitCode === 0 && /^[0-9a-f]{40,64}$/.test(sha) ? Option.some(sha) : Option.none() + }).pipe( + Effect.scoped, + Effect.orElseSucceed(() => Option.none()), + ) + +const remoteTarget = Effect.gen(function* () { + const config = yield* MapleConfig + const target = Option.all({ apiUrl: config.apiUrl, token: config.token }) + if (Option.isNone(target)) + return yield* new CliUsageError({ + message: "not logged in to a Maple workspace", + hint: "run `maple login`, or set MAPLE_API_URL and MAPLE_API_TOKEN", + }) + return { apiUrl: target.value.apiUrl, token: Redacted.value(target.value.token) } +}) + +const formatBytes = (n: number): string => + n >= 1024 * 1024 ? `${(n / 1024 / 1024).toFixed(1)} MiB` : `${(n / 1024).toFixed(1)} KiB` + +const reportOutcome = (outcome: UploadOutcome): Effect.Effect => { + switch (outcome._tag) { + case "uploaded": + return Console.log( + `uploaded ${outcome.minifiedPath} (${formatBytes(outcome.sizeBytes)}${Option.match(outcome.debugId, { onNone: () => "", onSome: (id) => `, ${id}` })})`, + ) + case "skipped": + return Console.error(`warning: skipped ${outcome.minifiedPath}: ${outcome.reason}`) + case "failed": + return Console.error(`failed ${outcome.minifiedPath}: ${outcome.error.message}`) + } +} + +/** Fails the command when nothing was uploaded or an upload failed, so CI stops there. */ +export const checkUploadOutcomes = ( + dir: string, + outcomes: ReadonlyArray, +): Effect.Effect => + Effect.gen(function* () { + const count = (tag: UploadOutcome["_tag"]) => Arr.filter(outcomes, (o) => o._tag === tag).length + if (outcomes.length === 0) + return yield* new CliUsageError({ + message: `no source maps with a matching JS file found under ${dir}`, + hint: "build with source maps enabled, then run `maple sourcemaps inject` on the output", + }) + if (count("skipped") === outcomes.length) + return yield* new CliUsageError({ + message: "no source maps were uploaded; every matching map was skipped", + hint: "check the skip warnings above", + }) + const firstFailure = Arr.findFirst(outcomes, (o) => o._tag === "failed") + if (Option.isSome(firstFailure) && firstFailure.value._tag === "failed") { + // Reported as the raw API errors so a 4xx reads as the request to fix, not a CLI fault. + const failed = firstFailure.value.error + const message = `${count("failed")} source map upload(s) failed; first: ${failed.minifiedPath}: ${failed.message}` + if (failed.status === undefined) return yield* new ApiTransportError({ message }) + return yield* failed.status === 401 + ? new ApiResponseError({ status: 401, message, hint: "run `maple login` again" }) + : new ApiResponseError({ status: failed.status, message }) + } + }) + +const upload = Command.make("upload", { + dir: dirArg, + service: Flag.optional( + Flag.String("service").pipe( + Flag.withDescription("Service name the maps belong to (OTel service.name)"), + ), + ), + release: Flag.optional( + Flag.String("release").pipe( + Flag.withDescription( + "Release the maps belong to (OTel service.version); defaults to `git rev-parse HEAD` when --service is set", + ), + ), + ), + urlPrefix: Flag.optional( + Flag.String("url-prefix").pipe( + Flag.withDescription( + "Path the files are served under, prepended to each file path, e.g. assets/", + ), + ), + ), +}).pipe( + Command.withDescription( + "Upload every source map in a build directory to the logged-in workspace so error stack traces show original source", + ), + Command.withHandler(({ dir, service, release, urlPrefix }) => + Effect.gen(function* () { + const { apiUrl, token } = yield* remoteTarget + const version = Option.isSome(release) || Option.isNone(service) ? release : yield* gitHead(dir) + const outcomes = yield* uploadDirectory( + dir, + { apiUrl, token, service, version, urlPrefix, concurrency: 4 }, + reportOutcome, + ) + const count = (tag: UploadOutcome["_tag"]) => Arr.filter(outcomes, (o) => o._tag === tag).length + const bytes = Arr.reduce(outcomes, 0, (sum, o) => + o._tag === "uploaded" ? sum + o.sizeBytes : sum, + ) + yield* Console.log( + `Uploaded ${count("uploaded")} source map(s) (${formatBytes(bytes)}); ${count("skipped")} skipped, ${count("failed")} failed`, + ) + return yield* checkUploadOutcomes(dir, outcomes) + }), + ), +) + +export const sourcemaps = Command.make("sourcemaps").pipe( + Command.withDescription("Prepare and upload JavaScript source maps for readable error stack traces"), + Command.withSubcommands([inject, upload]), +) diff --git a/apps/cli/src/core/sourcemaps-upload.test.ts b/apps/cli/src/core/sourcemaps-upload.test.ts new file mode 100644 index 0000000000..16a77591c0 --- /dev/null +++ b/apps/cli/src/core/sourcemaps-upload.test.ts @@ -0,0 +1,183 @@ +import { afterEach, beforeEach, describe, expect, test } from "bun:test" +import * as BunServices from "@effect/platform-bun/BunServices" +import { Array as Arr, Effect, Layer, Option, Record as Rec } from "effect" +import { FetchHttpClient } from "effect/http" +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { minifiedPathFor, uploadDirectory, type UploadOptions, type UploadOutcome } from "./sourcemaps-upload" + +interface Seen { + readonly url: URL + readonly authorization: string | null + readonly contentType: string | null + readonly body: string +} + +const servers: Array> = [] + +/** A local stand-in for `POST /v2/source_maps`, reached over the real fetch client. */ +const fakeServer = (answer: (url: URL) => Response) => { + const seen: Array = [] + const server = Bun.serve({ + port: 0, + fetch: async (request) => { + const url = new URL(request.url) + seen.push({ + url, + authorization: request.headers.get("authorization"), + contentType: request.headers.get("content-type"), + body: await request.text(), + }) + return answer(url) + }, + }) + servers.push(server) + return { seen, apiUrl: `http://127.0.0.1:${server.port}/` } +} + +const options = (overrides: Partial = {}): UploadOptions => ({ + apiUrl: "http://127.0.0.1:1/", + token: "maple_ak_test", + service: Option.none(), + version: Option.none(), + urlPrefix: Option.none(), + concurrency: 4, + ...overrides, +}) + +const upload = (dir: string, opts: UploadOptions) => + Effect.runPromise( + uploadDirectory(dir, opts, () => Effect.void).pipe( + Effect.provide(Layer.merge(FetchHttpClient.layer, BunServices.layer)), + ), + ) + +const ID = "0b1c2d3e-4f50-4617-8899-aabbccddeeff" +const mapWithId = JSON.stringify({ version: 3, sources: [], names: [], mappings: "AAAA", debugId: ID }) + +let dir = "" +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), "maple-sourcemaps-upload-")) +}) +afterEach(async () => { + rmSync(dir, { recursive: true, force: true }) + await Promise.all(Arr.map(servers.splice(0), (server) => server.stop(true))) +}) + +describe("minifiedPathFor", () => { + test("prepends the prefix with one slash and never starts with one", () => { + expect(minifiedPathFor(Option.some("assets/"), "index.js")).toBe("assets/index.js") + expect(minifiedPathFor(Option.some("/static"), "js/a.js")).toBe("static/js/a.js") + expect(minifiedPathFor(Option.none(), "a.js")).toBe("a.js") + }) +}) + +describe("uploadDirectory", () => { + test("posts each map as the raw body with its path, debug id, service and version", async () => { + mkdirSync(join(dir, "js")) + writeFileSync(join(dir, "js/index-Bx81.js"), `a()\n//# debugId=${ID}\n`) + writeFileSync(join(dir, "js/index-Bx81.js.map"), mapWithId) + writeFileSync(join(dir, "orphan.js.map"), mapWithId) + const server = fakeServer(() => + Response.json({ object: "source_map", id: "smap_1" }, { status: 201 }), + ) + + const outcomes = await upload( + dir, + options({ + apiUrl: server.apiUrl, + service: Option.some("web"), + version: Option.some("abc123"), + urlPrefix: Option.some("assets/"), + }), + ) + + expect(server.seen).toHaveLength(1) + const call = server.seen[0] + expect(call?.url.pathname).toBe("/v2/source_maps") + expect(Rec.fromEntries(Arr.fromIterable(call?.url.searchParams ?? []))).toEqual({ + minified_path: "assets/js/index-Bx81.js", + debug_id: ID, + service: "web", + version: "abc123", + }) + expect(call?.authorization).toBe("Bearer maple_ak_test") + expect(call?.body).toBe(mapWithId) + expect(call?.contentType).toBe("application/json") + expect(outcomes).toEqual([ + { + _tag: "uploaded", + minifiedPath: "assets/js/index-Bx81.js", + debugId: Option.some(ID), + sizeBytes: mapWithId.length, + id: Option.some("smap_1"), + }, + ]) + }) + + test("reads the debug id from the JS comment when the map has none", async () => { + writeFileSync(join(dir, "a.js"), `a()\n//# debugId=${ID}\n`) + writeFileSync(join(dir, "a.js.map"), JSON.stringify({ version: 3, mappings: "" })) + const server = fakeServer(() => Response.json({ id: "smap_2" })) + + await upload(dir, options({ apiUrl: server.apiUrl })) + + expect(server.seen[0]?.url.searchParams.get("debug_id")).toBe(ID) + expect(server.seen[0]?.url.searchParams.has("service")).toBe(false) + }) + + test("a refused upload carries the server's message and the rest still upload", async () => { + writeFileSync(join(dir, "bad.js"), "b()\n") + writeFileSync(join(dir, "bad.js.map"), JSON.stringify({ version: 3, mappings: "" })) + writeFileSync(join(dir, "good.js"), "g()\n") + writeFileSync(join(dir, "good.js.map"), mapWithId) + const server = fakeServer((url) => + url.searchParams.get("minified_path") === "bad.js" + ? Response.json({ error: { message: "mappings must be a string" } }, { status: 400 }) + : Response.json({ id: "smap_3" }), + ) + + const outcomes = await upload( + dir, + options({ apiUrl: server.apiUrl, service: Option.some("web"), version: Option.some("v1") }), + ) + + const byPath = Rec.fromEntries(Arr.map(outcomes, (o: UploadOutcome) => [o.minifiedPath, o] as const)) + const bad = byPath["bad.js"] + expect(bad?._tag).toBe("failed") + if (bad?._tag === "failed") { + expect(bad.error.status).toBe(400) + expect(bad.error.message).toBe("HTTP 400: mappings must be a string") + } + expect(byPath["good.js"]?._tag).toBe("uploaded") + }) + + test("skips a map with no debug id when there is no service and release to match it by", async () => { + writeFileSync(join(dir, "a.js"), "a()\n") + writeFileSync(join(dir, "a.js.map"), JSON.stringify({ version: 3, mappings: "" })) + const server = fakeServer(() => Response.json({ id: "smap_4" })) + + const outcomes = await upload(dir, options({ apiUrl: server.apiUrl, service: Option.some("web") })) + + expect(server.seen).toHaveLength(0) + expect(Arr.map(outcomes, (o) => o._tag)).toEqual(["skipped"]) + }) + + test("skips an index map, which the workspace refuses", async () => { + writeFileSync(join(dir, "a.js"), `a()\n//# debugId=${ID}\n`) + writeFileSync(join(dir, "a.js.map"), JSON.stringify({ version: 3, sections: [] })) + const server = fakeServer(() => Response.json({ id: "smap_5" })) + + const outcomes = await upload(dir, options({ apiUrl: server.apiUrl })) + + expect(server.seen).toHaveLength(0) + expect(outcomes).toEqual([ + { + _tag: "skipped", + minifiedPath: "a.js", + reason: "index source maps are not supported; emit a regular map", + }, + ]) + }) +}) diff --git a/apps/cli/src/core/sourcemaps-upload.ts b/apps/cli/src/core/sourcemaps-upload.ts new file mode 100644 index 0000000000..de703a9f00 --- /dev/null +++ b/apps/cli/src/core/sourcemaps-upload.ts @@ -0,0 +1,215 @@ +import { Array as Arr, Effect, Option, Result, Schema, String as Str } from "effect" +import { FileSystem } from "effect/FileSystem" +import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http" +import { sendTraced } from "../commands/api" +import { errorMessageOf, parseJson } from "./api-request" +import { + existingDebugId, + findJsFiles, + isIndexMap, + mapDebugId, + mapUsers, + MAX_MAP_BYTES, + SourceMapsFileError, +} from "./sourcemaps" + +/** One map the workspace refused, or that never reached it (no `status`). */ +export class SourceMapUploadError extends Schema.TaggedError()( + "@maple/cli/SourceMapUploadError", + { + message: Schema.String, + minifiedPath: Schema.String, + status: Schema.optionalKey(Schema.Number), + cause: Schema.optionalKey(Schema.Defect()), + }, +) {} + +export interface UploadOptions { + readonly apiUrl: string + readonly token: string + readonly service: Option.Option + readonly version: Option.Option + readonly urlPrefix: Option.Option + /** Parallel uploads; the command uses 4. */ + readonly concurrency: number +} + +export type UploadOutcome = + | { + readonly _tag: "uploaded" + readonly minifiedPath: string + readonly debugId: Option.Option + readonly sizeBytes: number + readonly id: Option.Option + } + | { readonly _tag: "skipped"; readonly minifiedPath: string; readonly reason: string } + | { readonly _tag: "failed"; readonly minifiedPath: string; readonly error: SourceMapUploadError } + +/** The JS file's path on the deploy, `--url-prefix` first, never with a leading slash. */ +export const minifiedPathFor = (urlPrefix: Option.Option, file: string): string => { + const prefix = Option.getOrElse(urlPrefix, () => "") + const joined = prefix === "" || Str.endsWith("/")(prefix) ? `${prefix}${file}` : `${prefix}/${file}` + return Str.replace(/^(?:~\/|\/)+/, "")(joined) +} + +/** The query string for one upload: debug id, service and version only when known. */ +export const uploadParams = (input: { + readonly minifiedPath: string + readonly debugId: Option.Option + readonly service: Option.Option + readonly version: Option.Option +}): ReadonlyArray => [ + ["minified_path", input.minifiedPath], + ...Option.toArray(Option.map(input.debugId, (id) => ["debug_id", id] as const)), + ...Option.toArray(Option.map(input.service, (s) => ["service", s] as const)), + ...Option.toArray(Option.map(input.version, (v) => ["version", v] as const)), +] + +const IdField = Schema.Struct({ id: Schema.String }) + +const send = ( + options: UploadOptions, + params: ReadonlyArray, + minifiedPath: string, + body: Uint8Array, +) => + Effect.gen(function* () { + const client = yield* HttpClient.HttpClient + const url = new URL(`${Str.replace(/\/+$/, "")(options.apiUrl)}/v2/source_maps`) + const request = HttpClientRequest.post(url.toString()).pipe( + HttpClientRequest.setUrlParams(params), + HttpClientRequest.setHeader("accept", "application/json"), + HttpClientRequest.bearerToken(options.token), + HttpClientRequest.bodyUint8Array(body, "application/json"), + ) + const response = yield* sendTraced(client, request, url).pipe( + Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }), + Effect.mapError( + (cause) => + new SourceMapUploadError({ + message: `could not reach ${url.origin}`, + minifiedPath, + cause, + }), + ), + ) + const text = yield* response.text.pipe(Effect.orElseSucceed(() => "")) + const json = text === "" ? Option.none() : Result.getSuccess(parseJson(text, "the response")) + if (response.status >= 200 && response.status < 300) + return Option.map( + Option.flatMap(json, (u) => Result.getSuccess(Schema.decodeUnknownResult(IdField)(u))), + (o) => o.id, + ) + const detail = Option.getOrElse(Option.flatMap(json, errorMessageOf), () => + Str.trim(text) === "" ? "no message" : Str.slice(0, 300)(Str.trim(text)), + ) + return yield* new SourceMapUploadError({ + message: `HTTP ${response.status}: ${detail}`, + minifiedPath, + status: response.status, + }) + }) + +/** + * Upload every map below `dir` whose JS file is there too, one upload per JS file. A map a file + * names outside `dir` is skipped, never read. `onOutcome` runs as each file finishes, + * so progress prints while the rest are still uploading. + */ +export const uploadDirectory = ( + dir: string, + options: UploadOptions, + onOutcome: (outcome: UploadOutcome) => Effect.Effect, +) => + Effect.gen(function* () { + const fs = yield* FileSystem + const files = yield* findJsFiles(dir) + const users = mapUsers(files) + const refused = Arr.flatMap(files, (js) => + Option.toArray( + Option.map(js.refusedMap, (mapPath): UploadOutcome => ({ + _tag: "skipped", + minifiedPath: minifiedPathFor(options.urlPrefix, js.file), + reason: `its source map ${mapPath} is outside ${dir}`, + })), + ), + ) + yield* Effect.forEach(refused, onOutcome, { discard: true }) + // A map two JS files share is uploaded once per file, each under its own path and id. + const withMaps = Arr.flatMap(files, (js) => + Option.toArray( + Option.map(js.mapPath, (mapPath) => ({ js, mapPath, shared: (users.get(mapPath) ?? 0) > 1 })), + ), + ) + const uploaded = yield* Effect.forEach( + withMaps, + ({ js, mapPath, shared }) => + Effect.gen(function* () { + const minifiedPath = minifiedPathFor(options.urlPrefix, js.file) + const info = yield* fs.stat(mapPath).pipe( + Effect.mapError( + (cause) => + new SourceMapsFileError({ + message: `could not read ${mapPath}`, + path: mapPath, + cause, + }), + ), + ) + if (info.size > BigInt(MAX_MAP_BYTES)) + return { + _tag: "skipped", + minifiedPath, + reason: `map is over ${MAX_MAP_BYTES / 1024 / 1024} MiB`, + } satisfies UploadOutcome + const body = yield* fs.readFile(mapPath).pipe( + Effect.mapError( + (cause) => + new SourceMapsFileError({ + message: `could not read ${mapPath}`, + path: mapPath, + cause, + }), + ), + ) + if (isIndexMap(new TextDecoder().decode(body))) + return { + _tag: "skipped", + minifiedPath, + reason: "index source maps are not supported; emit a regular map", + } satisfies UploadOutcome + // The file's own id is what its frames report; a shared map's id belongs to no one file. + const debugId = Option.orElse(existingDebugId(js.code), () => + shared ? Option.none() : mapDebugId(new TextDecoder().decode(body)), + ) + if ( + Option.isNone(debugId) && + (Option.isNone(options.service) || Option.isNone(options.version)) + ) + return { + _tag: "skipped", + minifiedPath, + reason: "no debug id; run `maple sourcemaps inject` first, or pass --service and --release", + } satisfies UploadOutcome + const params = uploadParams({ + minifiedPath, + debugId, + service: options.service, + version: options.version, + }) + return yield* send(options, params, minifiedPath, body).pipe( + Effect.map((id): UploadOutcome => ({ + _tag: "uploaded", + minifiedPath, + debugId, + sizeBytes: body.byteLength, + id, + })), + Effect.catchTag("@maple/cli/SourceMapUploadError", (error) => + Effect.succeed({ _tag: "failed", minifiedPath, error }), + ), + ) + }).pipe(Effect.tap(onOutcome)), + { concurrency: options.concurrency }, + ) + return [...refused, ...uploaded] + }) diff --git a/apps/cli/src/core/sourcemaps.test.ts b/apps/cli/src/core/sourcemaps.test.ts new file mode 100644 index 0000000000..95bb6308c9 --- /dev/null +++ b/apps/cli/src/core/sourcemaps.test.ts @@ -0,0 +1,449 @@ +import { afterEach, beforeEach, describe, expect, test } from "bun:test" +import * as BunServices from "@effect/platform-bun/BunServices" +import { Array as Arr, Effect, Layer, Option, Result, String as Str } from "effect" +import { FileSystem } from "effect/FileSystem" +import * as PlatformError from "effect/PlatformError" +import { FetchHttpClient } from "effect/http" +import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { canPrepend, debugIdFor, debugIdSnippet, existingDebugId, injectDirectory } from "./sourcemaps" +import { uploadDirectory } from "./sourcemaps-upload" + +const run = (effect: Effect.Effect) => + Effect.runPromise(Effect.provide(effect, BunServices.layer)) + +const map = (file: string, extra: Record = {}) => + JSON.stringify({ + version: 3, + file, + sources: ["../src/a.ts"], + names: [], + mappings: "AAAA,SAAS;AACT", + ...extra, + }) + +const read = (path: string) => readFileSync(path, "utf8") + +let dir = "" +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), "maple-sourcemaps-")) +}) +afterEach(() => rmSync(dir, { recursive: true, force: true })) + +const DIGITS = new Map( + Arr.map( + Arr.fromIterable("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"), + (c, i) => [c, i] as const, + ), +) + +/** The original (0-based) line the first segment of generated line `line` (1-based) maps to. */ +const originalLineAt = (mappings: string, line: number): number | undefined => { + const decode = (segment: string): ReadonlyArray => { + const values: Array = [] + const state = { value: 0, shift: 0 } + Arr.forEach(Arr.fromIterable(segment), (char) => { + const digit = DIGITS.get(char) ?? 0 + state.value += (digit & 31) << state.shift + state.shift += 5 + if ((digit & 32) === 0) { + values.push((state.value & 1) === 1 ? -(state.value >>> 1) : state.value >>> 1) + state.value = 0 + state.shift = 0 + } + }) + return values + } + // Source lines are deltas across the whole mappings string. + const lines = Str.split(";")(mappings) + const sourceLine = { value: 0 } + const found = { value: undefined as number | undefined } + Arr.forEach(lines, (generated, i) => { + Arr.forEach(generated === "" ? [] : Str.split(",")(generated), (segment, j) => { + const fields = decode(segment) + sourceLine.value += fields[2] ?? 0 + if (i === line - 1 && j === 0) found.value = sourceLine.value + }) + }) + return found.value +} + +describe("debugIdFor", () => { + test("is a lowercase UUID of the JS and its map, never of the map's own debug id", () => { + const id = debugIdFor("console.log(1)\n", map("a.js")) + expect(id).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/) + expect(debugIdFor("console.log(1)\n", map("a.js"))).toBe(id) + expect(debugIdFor("console.log(2)\n", map("a.js"))).not.toBe(id) + expect(debugIdFor("console.log(1)\n", map("a.js", { debugId: id, debug_id: id }))).toBe(id) + }) +}) + +describe("injectDirectory", () => { + test("registers first, tags the end and shifts the map one line", async () => { + mkdirSync(join(dir, "assets")) + const withUrl = "function a(){return 1}\n//# sourceMappingURL=index.js.map\n" + const bare = "export const b=2;" + writeFileSync(join(dir, "assets/index.js"), withUrl) + writeFileSync(join(dir, "assets/index.js.map"), map("index.js", { mappings: "AAAA;AACA" })) + writeFileSync(join(dir, "chunk.mjs"), bare) + writeFileSync(join(dir, "chunk.mjs.map"), map("chunk.mjs")) + writeFileSync(join(dir, "nomap.cjs"), "module.exports=1\n") + + const results = await run(injectDirectory(dir, { dryRun: false })) + + const idA = debugIdFor(withUrl, map("index.js", { mappings: "AAAA;AACA" })) + const idB = debugIdFor(bare, map("chunk.mjs")) + expect(read(join(dir, "assets/index.js"))).toBe( + `${debugIdSnippet(idA)}\nfunction a(){return 1}\n//# debugId=${idA}\n//# sourceMappingURL=index.js.map\n`, + ) + expect(read(join(dir, "chunk.mjs"))).toBe( + `${debugIdSnippet(idB)}\nexport const b=2;\n//# debugId=${idB}\n`, + ) + expect(read(join(dir, "nomap.cjs"))).toBe("module.exports=1\n") + + const mapA = JSON.parse(read(join(dir, "assets/index.js.map"))) + expect(mapA).toEqual({ + ...JSON.parse(map("index.js")), + mappings: ";AAAA;AACA", + debugId: idA, + debug_id: idA, + x_maple_shifted: idA, + }) + // `function a` was generated line 1 (original line 0) and is line 2 now; the next line follows. + expect([originalLineAt("AAAA;AACA", 1), originalLineAt("AAAA;AACA", 2)]).toEqual([0, 1]) + expect([ + originalLineAt(mapA.mappings, 1), + originalLineAt(mapA.mappings, 2), + originalLineAt(mapA.mappings, 3), + ]).toEqual([undefined, 0, 1]) + + expect(Arr.map(results, (r) => [r.file, r.status])).toEqual([ + ["assets/index.js", "injected"], + ["chunk.mjs", "injected"], + ["nomap.cjs", "no_map"], + ]) + }) + + test("appends after a shebang, a directive prologue or for an index map, leaving mappings alone", async () => { + const shebang = "#!/usr/bin/env node\nrun()\n" + const strict = '/*! license */\n"use strict";\nrun()\n' + const single = "'use client';\nrun()\n" + const indexed = "run()\n" + const sections = { + mappings: undefined, + sections: [{ offset: { line: 0, column: 0 }, map: JSON.parse(map("i.js")) }], + } + writeFileSync(join(dir, "a.js"), shebang) + writeFileSync(join(dir, "a.js.map"), map("a.js")) + writeFileSync(join(dir, "b.js"), strict) + writeFileSync(join(dir, "b.js.map"), map("b.js")) + writeFileSync(join(dir, "c.js"), single) + writeFileSync(join(dir, "c.js.map"), map("c.js")) + writeFileSync(join(dir, "i.js"), indexed) + writeFileSync(join(dir, "i.js.map"), map("i.js", sections)) + + const results = await run(injectDirectory(dir, { dryRun: false })) + const ids = Arr.map(results, (r) => Option.getOrElse(r.debugId, () => "")) + Arr.forEach([shebang, strict, single, indexed], (code, i) => { + const file = ["a.js", "b.js", "c.js", "i.js"][i] ?? "" + const id = ids[i] ?? "" + expect(read(join(dir, file))).toBe(`${code}${debugIdSnippet(id)}\n//# debugId=${id}\n`) + }) + expect(JSON.parse(read(join(dir, "a.js.map"))).mappings).toBe("AAAA,SAAS;AACT") + expect(JSON.parse(read(join(dir, "i.js.map"))).sections).toHaveLength(1) + + const again = await run(injectDirectory(dir, { dryRun: false })) + expect(Arr.map(again, (r) => [r.status, r.mapUpdated])).toEqual( + Arr.makeBy(4, () => ["already_injected", false]), + ) + }) + + test("reads a directive prologue past comments in one linear pass", () => { + expect(canPrepend('/*! a */\n// b\n "use strict";\nrun()')).toBe(false) + expect(canPrepend("/* a */ run('x')")).toBe(true) + const started = performance.now() + canPrepend(Str.repeat(100_000)("/*")) + canPrepend(`${Str.repeat(100_000)(" ")}x`) + expect(performance.now() - started).toBeLessThan(50) + }) + + test("converges after a failed JS write or a failed map write, moving the map once", async () => { + const code = "boom()\n" + const original = map("a.js", { mappings: "AAAA;AACA" }) + const failing = (failsOn: (path: string) => boolean) => + Layer.effect( + FileSystem, + Effect.gen(function* () { + const fs = yield* FileSystem + return { + ...fs, + writeFileString: ( + path: string, + data: string, + options?: Parameters[2], + ) => + failsOn(path) + ? Effect.fail( + PlatformError.systemError({ + _tag: "Unknown", + module: "FileSystem", + method: "writeFileString", + }), + ) + : fs.writeFileString(path, data, options), + } + }), + ).pipe(Layer.provideMerge(BunServices.layer)) + const injectWith = (failsOn: (path: string) => boolean) => + Effect.runPromise( + Effect.provide(Effect.result(injectDirectory(dir, { dryRun: false })), failing(failsOn)), + ) + const mappings = () => JSON.parse(read(join(dir, "a.js.map"))).mappings + + // The JS write fails after the map was moved: the next run must not move it again. + writeFileSync(join(dir, "a.js"), code) + writeFileSync(join(dir, "a.js.map"), original) + expect(Result.isFailure(await injectWith((path) => Str.endsWith("a.js")(path)))).toBe(true) + expect(read(join(dir, "a.js"))).toBe(code) + expect(mappings()).toBe(";AAAA;AACA") + const [repaired] = await run(injectDirectory(dir, { dryRun: false })) + const id = Option.getOrNull(repaired?.debugId ?? Option.none()) + expect(read(join(dir, "a.js"))).toBe(`${debugIdSnippet(id ?? "")}\nboom()\n//# debugId=${id}\n`) + expect(mappings()).toBe(";AAAA;AACA") + expect(JSON.parse(read(join(dir, "a.js.map"))).debugId).toBe(id) + const [again] = await run(injectDirectory(dir, { dryRun: false })) + expect([again?.status, again?.mapUpdated, mappings()]).toEqual([ + "already_injected", + false, + ";AAAA;AACA", + ]) + + // The map write fails: nothing changes, and the next run injects as if the first never ran. + writeFileSync(join(dir, "a.js"), code) + writeFileSync(join(dir, "a.js.map"), original) + expect(Result.isFailure(await injectWith((path) => Str.includes("a.js.map")(path)))).toBe(true) + expect([read(join(dir, "a.js")), read(join(dir, "a.js.map"))]).toEqual([code, original]) + await run(injectDirectory(dir, { dryRun: false })) + expect(mappings()).toBe(";AAAA;AACA") + }) + + test("repairs a registered file whose map lacks its id, moving the map once", async () => { + const id = "0b1c2d3e-4f50-4617-8899-aabbccddeeff" + writeFileSync(join(dir, "r.js"), `${debugIdSnippet(id)}\nr()\n//# debugId=${id}\n`) + writeFileSync(join(dir, "r.js.map"), map("r.js", { mappings: "AAAA" })) + + const [result] = await run(injectDirectory(dir, { dryRun: false })) + const repaired = JSON.parse(read(join(dir, "r.js.map"))) + expect([result?.status, result?.mapUpdated, repaired.mappings, repaired.debugId]).toEqual([ + "already_injected", + true, + ";AAAA", + id, + ]) + await run(injectDirectory(dir, { dryRun: false })) + expect(JSON.parse(read(join(dir, "r.js.map"))).mappings).toBe(";AAAA") + }) + + test("gives identical JS with different maps different ids", async () => { + mkdirSync(join(dir, "r1")) + mkdirSync(join(dir, "r2")) + const code = "throwIt()\n" + writeFileSync(join(dir, "r1/a.js"), code) + writeFileSync(join(dir, "r1/a.js.map"), map("a.js", { mappings: "AAAA" })) + writeFileSync(join(dir, "r2/a.js"), code) + writeFileSync(join(dir, "r2/a.js.map"), map("a.js", { mappings: "AACA" })) + + const [first] = await run(injectDirectory(join(dir, "r1"), { dryRun: false })) + const [second] = await run(injectDirectory(join(dir, "r2"), { dryRun: false })) + expect(Option.getOrNull(first?.debugId ?? Option.none())).not.toBe( + Option.getOrNull(second?.debugId ?? Option.none()), + ) + }) + + test("never writes an id into a map two files share, and uploads it once per file", async () => { + mkdirSync(join(dir, "maps")) + writeFileSync(join(dir, "app.js"), "a()\n//# sourceMappingURL=maps/app.map\n") + writeFileSync(join(dir, "app-legacy.js"), "b()\n//# sourceMappingURL=maps/app.map\n") + writeFileSync(join(dir, "maps/app.map"), map("app.js")) + + const results = await run(injectDirectory(dir, { dryRun: false })) + expect(read(join(dir, "maps/app.map"))).toBe(map("app.js")) + const ids = Arr.map(results, (r) => Option.getOrNull(r.debugId)) + expect(ids[0]).not.toBe(ids[1]) + // The lines did not move: the snippet went after the code. + expect(Str.startsWith("b()\n")(read(join(dir, "app-legacy.js")))).toBe(true) + + const seen: Array = [] + const server = Bun.serve({ + port: 0, + fetch: (request) => { + seen.push(new URL(request.url).searchParams) + return Response.json({ id: "smap_1" }) + }, + }) + const outcomes = await Effect.runPromise( + uploadDirectory( + dir, + { + apiUrl: `http://127.0.0.1:${server.port}`, + token: "t", + service: Option.none(), + version: Option.none(), + urlPrefix: Option.none(), + concurrency: 1, + }, + () => Effect.void, + ).pipe(Effect.provide(Layer.merge(FetchHttpClient.layer, BunServices.layer))), + ) + await server.stop(true) + expect(Arr.map(outcomes, (o) => o._tag)).toEqual(["uploaded", "uploaded"]) + // Each file is uploaded under its own path with the id its own snippet registers. + expect(Arr.map(seen, (params) => [params.get("minified_path"), params.get("debug_id")])).toEqual( + Arr.map(results, (r) => [r.file, Option.getOrNull(r.debugId)]), + ) + }) + + test("refuses a map outside the build directory, by path or by symlink", async () => { + const build = join(dir, "dist") + mkdirSync(build) + const outside = join(dir, "secret.json") + writeFileSync(outside, JSON.stringify({ version: 3, sources: ["x"], mappings: "AAAA" })) + writeFileSync(join(build, "up.js"), "u()\n//# sourceMappingURL=../secret.json\n") + writeFileSync(join(build, "abs.js"), `v()\n//# sourceMappingURL=${outside}\n`) + writeFileSync(join(build, "link.js"), "w()\n") + symlinkSync(outside, join(build, "link.js.map")) + writeFileSync(join(build, "pkg.js"), "p()\n") + writeFileSync(join(build, "pkg.js.map"), JSON.stringify({ name: "not-a-map" })) + + const results = await run(injectDirectory(build, { dryRun: false })) + + expect(Arr.map(results, (r) => [r.file, r.status])).toEqual([ + ["abs.js", "unsafe_map"], + ["link.js", "unsafe_map"], + ["pkg.js", "invalid_map"], + ["up.js", "unsafe_map"], + ]) + expect(read(outside)).toBe(JSON.stringify({ version: 3, sources: ["x"], mappings: "AAAA" })) + expect(read(join(build, "pkg.js.map"))).toBe(JSON.stringify({ name: "not-a-map" })) + expect(read(join(build, "up.js"))).toBe("u()\n//# sourceMappingURL=../secret.json\n") + }) + + test("keeps an existing registered debug id and is a no-op on a second run", async () => { + const existing = "0b1c2d3e-4f50-4617-8899-aabbccddeeff" + const injected = `y()\n${debugIdSnippet(existing)}\n//# debugId=${existing}\n//# sourceMappingURL=y.js.map\n` + writeFileSync(join(dir, "y.js"), injected) + writeFileSync(join(dir, "y.js.map"), map("y.js")) + writeFileSync(join(dir, "z.js"), "z()\n") + writeFileSync(join(dir, "z.js.map"), map("z.js")) + + const first = await run(injectDirectory(dir, { dryRun: false })) + expect(read(join(dir, "y.js"))).toBe(injected) + expect(JSON.parse(read(join(dir, "y.js.map"))).debug_id).toBe(existing) + expect(Arr.map(first, (r) => r.status)).toEqual(["already_injected", "injected"]) + + const zAfterFirst = read(join(dir, "z.js")) + const zMapAfterFirst = read(join(dir, "z.js.map")) + const second = await run(injectDirectory(dir, { dryRun: false })) + expect(Arr.map(second, (r) => [r.status, r.mapUpdated])).toEqual([ + ["already_injected", false], + ["already_injected", false], + ]) + expect(read(join(dir, "z.js"))).toBe(zAfterFirst) + expect(read(join(dir, "z.js.map"))).toBe(zMapAfterFirst) + expect(existingDebugId(zAfterFirst)).toEqual(Option.some(debugIdFor("z()\n", map("z.js")))) + }) + + test("keeps the id a runtime registration carries without a comment", async () => { + const existing = "0b1c2d3e-4f50-4617-8899-aabbccddeeff" + const registered = `${debugIdSnippet(existing)}\nr()\n` + writeFileSync(join(dir, "r.js"), registered) + writeFileSync(join(dir, "r.js.map"), map("r.js")) + + const [result] = await run(injectDirectory(dir, { dryRun: false })) + + expect(Option.getOrNull(result?.debugId ?? Option.none())).toBe(existing) + expect(read(join(dir, "r.js"))).toBe(registered) + expect(JSON.parse(read(join(dir, "r.js.map"))).debugId).toBe(existing) + }) + + test("registers a bundler's bare debugId comment at runtime, reusing its id", async () => { + const existing = "0b1c2d3e-4f50-4617-8899-aabbccddeeff" + // Rollup/Vite `sourcemapDebugIds` output: the comment, nothing that runs. + const v = `v()\n//# debugId=${existing}\n//# sourceMappingURL=v.js.map\n` + writeFileSync(join(dir, "v.js"), v) + writeFileSync(join(dir, "v.js.map"), map("v.js")) + writeFileSync(join(dir, "w.js"), `w()\n//# debugId=${existing}\n//# sourceMappingURL=w.js.map\n`) + writeFileSync(join(dir, "w.js.map"), map("w.js", { debugId: existing })) + + const results = await run(injectDirectory(dir, { dryRun: false })) + + expect(read(join(dir, "v.js"))).toBe(`${debugIdSnippet(existing)}\n${v}`) + const vMap = JSON.parse(read(join(dir, "v.js.map"))) + expect([vMap.debugId, vMap.debug_id, vMap.mappings]).toEqual([existing, existing, ";AAAA,SAAS;AACT"]) + expect(Arr.map(results, (r) => [r.file, r.status, Option.getOrNull(r.debugId)])).toEqual([ + ["v.js", "injected", existing], + ["w.js", "injected", existing], + ]) + expect(JSON.parse(read(join(dir, "w.js.map"))).debug_id).toBe(existing) + + const again = await run(injectDirectory(dir, { dryRun: false })) + expect(Arr.map(again, (r) => [r.status, r.mapUpdated])).toEqual([ + ["already_injected", false], + ["already_injected", false], + ]) + expect(JSON.parse(read(join(dir, "v.js.map"))).mappings).toBe(";AAAA,SAAS;AACT") + }) + + test("does not take a bundled SDK reading the debug id map for this file's registration", async () => { + const existing = "0b1c2d3e-4f50-4617-8899-aabbccddeeff" + const sdk = "var o=owner._mapleDebugIds||owner._sentryDebugIds;o&&(ids[o[k]]=k);" + const code = `${sdk}\n//# debugId=${existing}\n//# sourceMappingURL=sdk.js.map\n` + writeFileSync(join(dir, "sdk.js"), code) + writeFileSync(join(dir, "sdk.js.map"), map("sdk.js")) + + const [result] = await run(injectDirectory(dir, { dryRun: false })) + + expect(result?.status).toBe("injected") + expect(read(join(dir, "sdk.js"))).toBe(`${debugIdSnippet(existing)}\n${code}`) + const [again] = await run(injectDirectory(dir, { dryRun: false })) + expect(again?.status).toBe("already_injected") + }) + + test("handles CRLF line endings and a missing trailing newline", async () => { + const crlf = "c()\r\n//# sourceMappingURL=c.js.map\r\n" + const noNewline = "d()\n//# sourceMappingURL=d.js.map" + const existing = "0b1c2d3e-4f50-4617-8899-aabbccddeeff" + const crlfBare = `e()\r\n//# debugId=${existing}\r\n//# sourceMappingURL=e.js.map` + writeFileSync(join(dir, "c.js"), crlf) + writeFileSync(join(dir, "c.js.map"), map("c.js")) + writeFileSync(join(dir, "d.js"), noNewline) + writeFileSync(join(dir, "d.js.map"), map("d.js")) + writeFileSync(join(dir, "e.js"), crlfBare) + writeFileSync(join(dir, "e.js.map"), map("e.js")) + + const results = await run(injectDirectory(dir, { dryRun: false })) + + const idC = debugIdFor(crlf, map("c.js")) + const idD = debugIdFor(noNewline, map("d.js")) + expect(read(join(dir, "c.js"))).toBe( + `${debugIdSnippet(idC)}\nc()\r\n//# debugId=${idC}\n//# sourceMappingURL=c.js.map\r\n`, + ) + expect(read(join(dir, "d.js"))).toBe( + `${debugIdSnippet(idD)}\nd()\n//# debugId=${idD}\n//# sourceMappingURL=d.js.map`, + ) + expect(read(join(dir, "e.js"))).toBe(`${debugIdSnippet(existing)}\n${crlfBare}`) + expect(Arr.map(results, (r) => Option.getOrNull(r.debugId))).toEqual([idC, idD, existing]) + }) + + test("--dry-run reports the change and writes nothing", async () => { + writeFileSync(join(dir, "a.js"), "a()\n") + writeFileSync(join(dir, "a.js.map"), map("a.js")) + + const [result] = await run(injectDirectory(dir, { dryRun: true })) + + expect(result?.status).toBe("injected") + expect(read(join(dir, "a.js"))).toBe("a()\n") + expect(read(join(dir, "a.js.map"))).toBe(map("a.js")) + }) +}) diff --git a/apps/cli/src/core/sourcemaps.ts b/apps/cli/src/core/sourcemaps.ts new file mode 100644 index 0000000000..9694389f44 --- /dev/null +++ b/apps/cli/src/core/sourcemaps.ts @@ -0,0 +1,7 @@ +// `maple sourcemaps inject|upload`: the inject core is shared with the Alchemy Vite plugin. +import { SOURCE_MAP_MAX_BYTES } from "@maple/domain/http" + +export * from "@maple/sourcemaps" + +/** Maps above this are refused by the server (the largest it can symbolicate with), so they are skipped before the upload. */ +export const MAX_MAP_BYTES = SOURCE_MAP_MAX_BYTES diff --git a/apps/ios/Packages/MapleAPI/Sources/MapleAPI/openapi.json b/apps/ios/Packages/MapleAPI/Sources/MapleAPI/openapi.json index cfd2730a62..9cac8d4f4f 100644 --- a/apps/ios/Packages/MapleAPI/Sources/MapleAPI/openapi.json +++ b/apps/ios/Packages/MapleAPI/Sources/MapleAPI/openapi.json @@ -4656,6 +4656,9 @@ "last_seen_at": { "type": "string" }, + "latest_stack": { + "$ref": "#/components/schemas/SymbolicatedStack" + }, "latest_stacktrace": { "type": "string" }, @@ -6275,6 +6278,98 @@ "title": "Span", "type": "object" }, + "SymbolicatedStack": { + "additionalProperties": false, + "description": "A JavaScript stack trace mapped through uploaded source maps, top of stack first. `status` is `resolved` when every frame with a file mapped, `partial` when some did, `missing_map` when none did (`missing` lists the files with no map) and `not_applicable` when the trace has no JavaScript frames.", + "properties": { + "frames": { + "items": { + "additionalProperties": false, + "properties": { + "column": { + "type": "number" + }, + "context": { + "additionalProperties": false, + "properties": { + "line": { + "type": "string" + }, + "post": { + "items": { + "type": "string" + }, + "type": "array" + }, + "pre": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "pre", + "line", + "post" + ], + "type": "object" + }, + "file": { + "type": "string" + }, + "function": { + "type": "string" + }, + "function_from_map": { + "type": "boolean" + }, + "in_app": { + "type": "boolean" + }, + "line": { + "type": "number" + }, + "raw": { + "type": "string" + }, + "resolved": { + "type": "boolean" + } + }, + "required": [ + "raw", + "in_app", + "resolved" + ], + "type": "object" + }, + "type": "array" + }, + "missing": { + "items": { + "type": "string" + }, + "type": "array" + }, + "status": { + "enum": [ + "resolved", + "partial", + "missing_map", + "not_applicable" + ], + "type": "string" + } + }, + "required": [ + "status", + "frames", + "missing" + ], + "title": "Symbolicated stack", + "type": "object" + }, "TimeseriesSeries": { "additionalProperties": false, "properties": { @@ -14233,6 +14328,10 @@ "description": "Ingest-time attribute rewrite rules. Move or copy span/resource attribute values to new keys as telemetry arrives, normalizing naming across services without redeploying them.", "name": "Attribute Mappings" }, + { + "description": "JavaScript source maps for symbolicating browser errors. Upload one per built file from CI (`maple sourcemaps upload`), list them, or delete them. Any member may list; uploading and deleting take an engineer or admin.", + "name": "Source Maps" + }, { "description": "Databases and APIs your organization connects so Maple and its agents can query them in place. Nothing is imported. Members can read sources and catalogs; connecting, editing, testing and curating take an admin.", "name": "Data Sources" diff --git a/apps/org-eraser/src/tick.ts b/apps/org-eraser/src/tick.ts index 82a74fa182..c36924b548 100644 --- a/apps/org-eraser/src/tick.ts +++ b/apps/org-eraser/src/tick.ts @@ -3,7 +3,7 @@ * stays off the Worker's startup. */ import type * as Cloudflare from "@alchemy.run/cloudflare" -import { ReplayBlobEraser } from "@maple/backend/platform/bindings" +import { ReplayBlobEraser, SourceMapEraser } from "@maple/backend/platform/bindings" import { type ChatSessionNamespace, layerChatSessions } from "@maple/backend/platform/chat-sessions" import { DatabasePgLive } from "@maple/backend/platform/DatabasePgLive" import { layerMapleDbConnection } from "@maple/backend/platform/pg-connection-source" @@ -20,6 +20,7 @@ export const runTick = ( env: Record, chatSessions: ChatSessionNamespace, replayBlobs: Cloudflare.R2.ReadWriteBucketClient, + sourceMaps: Cloudflare.R2.ReadWriteBucketClient, ) => { const config = workerEnvLayer(env) const connection = layerMapleDbConnection(env) @@ -28,6 +29,7 @@ export const runTick = ( connection, layerChatSessions(chatSessions, env), Layer.succeed(ReplayBlobEraser, prefixEraser(replayBlobs)), + Layer.succeed(SourceMapEraser, prefixEraser(sourceMaps)), WarehouseDeleteClient.layer.pipe( Layer.provide([WarehouseDeleteToken.layer, FetchHttpClient.layer]), Layer.provide(config), diff --git a/apps/org-eraser/src/worker.ts b/apps/org-eraser/src/worker.ts index cbefe478df..aefb5ead63 100644 --- a/apps/org-eraser/src/worker.ts +++ b/apps/org-eraser/src/worker.ts @@ -4,7 +4,14 @@ * fetch refused), because it alone holds the warehouse delete token and a delete-capable binding * to the replay bucket. */ -import { MapleDb, mapleDbEnv, MapleStack, mapleWorkerProps, ReplayBlobs } from "@maple/infra/cloudflare" +import { + MapleDb, + mapleDbEnv, + MapleStack, + mapleWorkerProps, + ReplayBlobs, + SourceMapsBucket, +} from "@maple/infra/cloudflare" import { cachedRecoverable } from "@maple/infra/cached-recoverable" import { resolveWorkerEnv } from "@maple/infra/secret-guard" import { WORKER_PURE_OPTIONS } from "@maple/infra/worker-build" @@ -58,13 +65,14 @@ export default class OrgEraser extends Cloudflare.Worker()( // maple-ai's chat Durable Object, whose conversations are erased. const chatSessions = yield* bindChatSessions const replayBlobs = yield* Cloudflare.R2.ReadWriteBucket(ReplayBlobs) + const sourceMaps = yield* Cloudflare.R2.ReadWriteBucket(SourceMapsBucket) const onFire = () => Effect.gen(function* () { const env = yield* Cloudflare.WorkerEnvironment if (!(yield* isProduction(env))) return const { runTick } = yield* tick - yield* runTick(env, chatSessions, replayBlobs) + yield* runTick(env, chatSessions, replayBlobs, sourceMaps) }).pipe( // Interrupts are isolate teardown, not a failed run; the next fire picks up the rest. Effect.catchCause((cause) => diff --git a/apps/web/source-maps-dir.ts b/apps/web/source-maps-dir.ts new file mode 100644 index 0000000000..ab38d2e2f4 --- /dev/null +++ b/apps/web/source-maps-dir.ts @@ -0,0 +1,2 @@ +/** Where the web build's client source maps go, relative to the repo root: outside the deployed assets. */ +export const WEB_SOURCE_MAPS_DIR = "apps/web/.maple/sourcemaps/client" diff --git a/apps/web/src/data/error-issues.ts b/apps/web/src/data/error-issues.ts index 149e33d167..c1880aa0be 100644 --- a/apps/web/src/data/error-issues.ts +++ b/apps/web/src/data/error-issues.ts @@ -145,4 +145,6 @@ export const errorIssueDetailFromV2 = (detail: V2ErrorIssueDetail): ErrorIssueDe (env) => new ErrorIssueEnvironment({ name: env.name, count: env.count }), ), latestStacktrace: detail.latest_stacktrace ?? null, + // Absent from an API deployed before source maps. + latestStack: detail.latest_stack ?? null, }) diff --git a/apps/web/src/lab/entries/error-issue.ts b/apps/web/src/lab/entries/error-issue.ts index c2b86b50a9..3b432d4031 100644 --- a/apps/web/src/lab/entries/error-issue.ts +++ b/apps/web/src/lab/entries/error-issue.ts @@ -8,6 +8,7 @@ import { ErrorIssueVerificationsResponse, IssueEscalationAttemptsResponse, } from "@maple/domain/http" +import type { SymbolicatedStack } from "@maple/domain/errors/js-stack" import { encodePublicId, V2ErrorIssueDetail } from "@maple/domain/http/v2" import { Effect, Option, Result, Schema, Array as Arr, String as Str } from "effect" import { Command } from "foldkit" @@ -35,7 +36,8 @@ import { // with a regression, as a member or an analyst, who reads it and gets no triage control // (`?role=member|analyst&tab=overview|occurrences|activity|grouping`; `context=none` drops the samples' // release and user, for the table's setup prompt; `grouping=populated|long|empty|loading|error` picks -// what the Grouping tab's reads answer). API Commands are dropped; the page +// what the Grouping tab's reads answer; `stack=raw|resolved|partial|missing_map` picks the source map +// state of the newest stack trace). API Commands are dropped; the page // is sent the answers its reads would get. const context: PageContext = { @@ -155,6 +157,228 @@ const detailWithoutContext: typeof detail = { })), } +const MINIFIED_STACK = Arr.join( + [ + "TypeError: Cannot read properties of undefined (reading 'plan')", + " at Kc (https://app.acme.dev/assets/index-Bx81.js:1:48213)", + " at Object.renew (https://app.acme.dev/assets/index-Bx81.js:1:51877)", + " at Ln (https://app.acme.dev/assets/vendor-9d2c.js:2:10442)", + " at Pn (https://app.acme.dev/assets/vendor-9d2c.js:2:10661)", + " at Hn (https://app.acme.dev/assets/vendor-9d2c.js:2:11020)", + " at async Wd (https://app.acme.dev/assets/index-Bx81.js:1:60115)", + " at async https://app.acme.dev/assets/vendor-9d2c.js:2:30077", + ], + "\n", +) + +const rawLines = Arr.drop(Str.split(MINIFIED_STACK, "\n"), 1) + +/** A frame as the backend writes it; `raw` is the matching minified line. */ +const frame = ( + index: number, + fields: Readonly<{ + function: string | null + file: string + line: number + column: number + in_app: boolean + resolved: boolean + context?: Readonly<{ pre: ReadonlyArray; line: string; post: ReadonlyArray }> + }>, +) => ({ + raw: Str.trim(rawLines[index] ?? ""), + function: fields.function, + file: fields.file, + line: fields.line, + column: fields.column, + in_app: fields.in_app, + resolved: fields.resolved, + context: fields.context ?? null, +}) + +const resolvePlanContext = { + pre: [ + "export const resolvePlan = (account: Account, catalog: PlanCatalog): Plan => {", + '\tconst subscription = account.subscriptions.find((s) => s.status === "active")', + "\t// A trial account has no paid subscription yet.", + '\tconst tier = subscription?.tier ?? "trial"', + "", + ], + line: "\treturn catalog[tier].plan", + post: [ + "}", + "", + "export const planLimits = (plan: Plan) => ({", + "\tseats: plan.seats,", + "\tevents: plan.events,", + ], +} + +const renewContext = { + pre: [ + "\tasync renew(accountId: AccountId) {", + "\t\tconst account = await this.accounts.get(accountId)", + "\t\tconst catalog = await this.catalog.current()", + "", + "\t\t// The plan decides the renewal price.", + ], + line: "\t\tconst plan = resolvePlan(account, catalog)", + post: [ + "\t\treturn this.billing.charge(account, plan.price)", + "\t}", + "", + "\tasync cancel(accountId: AccountId) {", + "\t\tconst account = await this.accounts.get(accountId)", + ], +} + +const libraryFrames = [ + frame(2, { + function: "dispatch", + file: "node_modules/hono/dist/compose.js", + line: 30, + column: 17, + in_app: false, + resolved: true, + }), + frame(3, { + function: "Hono.fetch", + file: "node_modules/hono/dist/hono-base.js", + line: 188, + column: 23, + in_app: false, + resolved: true, + }), + frame(4, { + function: "handle", + file: "node_modules/hono/dist/adapter/handle.js", + line: 12, + column: 9, + in_app: false, + resolved: true, + }), +] + +const topFrames = [ + frame(0, { + function: "resolvePlan", + file: "src/billing/plan.ts", + line: 47, + column: 28, + in_app: true, + resolved: true, + context: resolvePlanContext, + }), + frame(1, { + function: "SubscriptionService.renew", + file: "src/billing/subscription-service.ts", + line: 118, + column: 19, + in_app: true, + resolved: true, + context: renewContext, + }), +] + +const handleRenewalFrame = frame(5, { + function: "handleRenewal", + file: "src/routes/renewals.ts", + line: 31, + column: 5, + in_app: true, + resolved: true, + context: { + pre: ["export const handleRenewal = async (c: Context) => {"], + line: '\tawait subscriptions.renew(c.req.param("id"))', + post: ["\treturn c.json({ ok: true })", "}"], + }, +}) + +const resolvedStack: SymbolicatedStack = { + status: "resolved", + frames: [ + ...topFrames, + ...libraryFrames, + handleRenewalFrame, + frame(6, { + function: null, + file: "node_modules/hono/dist/router.js", + line: 74, + column: 11, + in_app: false, + resolved: true, + }), + ], + missing: [], +} + +/** The app bundle has a map; the vendor bundle does not, so its frames stay minified. */ +const partialStack: SymbolicatedStack = { + status: "partial", + frames: [ + ...topFrames, + frame(2, { + function: "Ln", + file: "https://app.acme.dev/assets/vendor-9d2c.js", + line: 2, + column: 10442, + in_app: false, + resolved: false, + }), + frame(3, { + function: "Pn", + file: "https://app.acme.dev/assets/vendor-9d2c.js", + line: 2, + column: 10661, + in_app: false, + resolved: false, + }), + frame(4, { + function: "Hn", + file: "https://app.acme.dev/assets/vendor-9d2c.js", + line: 2, + column: 11020, + in_app: false, + resolved: false, + }), + handleRenewalFrame, + ], + missing: ["https://app.acme.dev/assets/vendor-9d2c.js"], +} + +const missingMapStack: SymbolicatedStack = { + status: "missing_map", + frames: Arr.map(rawLines, (raw) => ({ + raw: Str.trim(raw), + function: null, + file: null, + line: null, + column: null, + in_app: true, + resolved: false, + context: null, + })), + missing: ["https://app.acme.dev/assets/index-Bx81.js", "https://app.acme.dev/assets/vendor-9d2c.js"], +} + +/** The same issue as each source map state would answer it; `raw` is an API with no symbolicated stack. */ +const STACKS = ["raw", "resolved", "partial", "missing_map"] as const +type StackState = (typeof STACKS)[number] + +const withStack = (base: typeof detail, state: StackState): typeof detail => + state === "raw" + ? base + : Schema.decodeSync(V2ErrorIssueDetail)({ + ...Schema.encodeSync(V2ErrorIssueDetail)(base), + latest_stacktrace: MINIFIED_STACK, + latest_stack: + state === "resolved" + ? resolvedStack + : state === "partial" + ? partialStack + : missingMapStack, + }) + /** Reads, writes and the window resolve go to the API; the lab answers them itself. */ const isLocalCommand = (command: { readonly name: string }): boolean => !/^(Fetch|Run|Create|Link|Unlink|Comment|Evaluate|ResolveIssueWindow)/.test(command.name) @@ -177,6 +401,7 @@ const Flags = Schema.Struct({ tab: Schema.Literals(TABS), context: Schema.Literals(CONTEXTS), grouping: Schema.Literals(GROUPING_STATES), + stack: Schema.Literals(STACKS), }) type Flags = typeof Flags.Type type LabRole = Flags["role"] @@ -186,6 +411,7 @@ const decodeRole = Schema.decodeUnknownOption(Schema.Literals(ROLES)) const decodeTab = Schema.decodeUnknownOption(Schema.Literals(TABS)) const decodeContext = Schema.decodeUnknownOption(Schema.Literals(CONTEXTS)) const decodeGrouping = Schema.decodeUnknownOption(Schema.Literals(GROUPING_STATES)) +const decodeStack = Schema.decodeUnknownOption(Schema.Literals(STACKS)) const LAB_FAILURE = toLoadFailure("Maple couldn't query your telemetry.") @@ -224,7 +450,9 @@ const init = (flags: Flags) => { [ Message.CompletedFetchDetail({ key: keyOf("detail"), - result: Result.succeed(flags.context === "none" ? detailWithoutContext : detail), + result: Result.succeed( + withStack(flags.context === "none" ? detailWithoutContext : detail, flags.stack), + ), }), Message.CompletedFetchAffectedUsers({ key: keyOf("affectedUsers"), @@ -335,6 +563,7 @@ export const lab = defineShellLab("Error issue", { decodeGrouping(params.get("grouping")), (): GroupingState => "populated", ), + stack: Option.getOrElse(decodeStack(params.get("stack")), (): StackState => "raw"), } }), init, diff --git a/apps/web/src/lab/registry.ts b/apps/web/src/lab/registry.ts index 2bc1f182f7..57223d9c17 100644 --- a/apps/web/src/lab/registry.ts +++ b/apps/web/src/lab/registry.ts @@ -639,7 +639,7 @@ export const LAB_ENTRIES: ReadonlyArray = [ path: "/lab/error-issue", title: "Error issue", description: - "The error issue page over one surging, regressed high-severity TypeError: the occurrence chart and its tooltip, the Get it fixed panel, the stat rail and the rail. The Grouping tab shows every fingerprint rule and source, a pinned fingerprint, a long frame list and similar issues (?grouping=populated|long|empty|loading|error). As a member or an analyst, who reads it and gets no triage control (?role=member|analyst&tab=overview|occurrences|activity|grouping).", + "The error issue page over one surging, regressed high-severity TypeError: the occurrence chart and its tooltip, the Get it fixed panel, the stat rail and the rail. The Grouping tab shows every fingerprint rule and source, a pinned fingerprint, a long frame list and similar issues (?grouping=populated|long|empty|loading|error). The stack trace in each source map state (?stack=raw|resolved|partial|missing_map). As a member or an analyst, who reads it and gets no triage control (?role=member|analyst&tab=overview|occurrences|activity|grouping).", kind: "lab", session: "none", }, diff --git a/apps/web/src/page/errors/issue/message.ts b/apps/web/src/page/errors/issue/message.ts index 15df422e42..b24d841b79 100644 --- a/apps/web/src/page/errors/issue/message.ts +++ b/apps/web/src/page/errors/issue/message.ts @@ -76,6 +76,8 @@ export const Message = defineMessageUnion({ ClickedRetryGrouping: {}, ClickedRetrySimilar: {}, ToggledSkippedFrames: { fingerprintHash: Schema.String }, + ToggledStackRow: { key: Schema.String }, + ToggledRawStack: {}, ClickedSplitOut: { fingerprintHash: Schema.String }, CompletedSplitOut: { fingerprintHash: Schema.String, result: Schema.Result(Schema.Null, LoadFailure) }, ClickedMergeSimilar: { sourceIssueId: ErrorIssueId }, diff --git a/apps/web/src/page/errors/issue/model.ts b/apps/web/src/page/errors/issue/model.ts index 93f1bdd43b..d9c609304b 100644 --- a/apps/web/src/page/errors/issue/model.ts +++ b/apps/web/src/page/errors/issue/model.ts @@ -59,6 +59,10 @@ export const Model = Schema.Struct({ similar: keyed(ErrorIssueSimilarResponse), /** Fingerprints whose skipped frames are shown. */ openSkippedFrames: Schema.Array(Schema.String), + /** The stack trace's rows flipped from their default (the top app frame open, the rest closed). */ + stackToggles: Schema.Array(Schema.String), + /** The symbolicated stack is swapped for the raw text as the SDK sent it. */ + isShowingRawStack: Schema.Boolean, /** The fingerprint being split out, while its detach is in flight. */ splittingHash: Schema.NullOr(Schema.String), /** The similar issue being merged into this one, while the merge is in flight. */ diff --git a/apps/web/src/page/errors/issue/stack-trace.scene.test.ts b/apps/web/src/page/errors/issue/stack-trace.scene.test.ts new file mode 100644 index 0000000000..87db928b02 --- /dev/null +++ b/apps/web/src/page/errors/issue/stack-trace.scene.test.ts @@ -0,0 +1,231 @@ +import { OrgId } from "@maple/domain" +import type { SymbolicatedStack } from "@maple/domain/errors/js-stack" +import { ErrorIssueId } from "@maple/domain/http" +import { encodePublicId, V2ErrorIssueDetail } from "@maple/domain/http/v2" +import { Option, Result, Schema } from "effect" +import type { Html, HtmlBuilder } from "foldkit/html" +import { click, expect as expectView, given, role, scene, selector, text } from "foldkit/scene" +import { describe, expect, test } from "vitest" +import type { PageContext } from "../../contract" +import { detailOf } from "./derive" +import { Message } from "./message" +import type { Model } from "./model" +import { init, update } from "./update" +import { exceptionPanel } from "./view-overview" + +// The exception panel's stack: mapped frames when a source map matched, the raw text otherwise. + +const orgId = Schema.decodeSync(OrgId)("org_acme") +const issueId = Schema.decodeSync(ErrorIssueId)("0199a004-0000-7000-8000-000000000001") +const context: PageContext = { orgId, pinnedNamespace: null, timeZone: "UTC" } +const window = { startTime: "2026-10-01 00:00:00", endTime: "2026-10-01 12:00:00" } +const NOW = Date.UTC(2026, 9, 1, 12) +const pageUpdate = (model: Model, message: Message) => update(model, message, context) + +const RAW = "TypeError: x is undefined\n at Kc (https://app.acme.dev/assets/index-Bx81.js:1:48213)" + +const frame = ( + fields: Partial & { function: string }, +): SymbolicatedStack["frames"][number] => ({ + raw: `at ${fields.function}`, + file: "src/billing/plan.ts", + line: 10, + column: 3, + in_app: true, + resolved: true, + context: null, + ...fields, +}) + +const resolved: SymbolicatedStack = { + status: "resolved", + frames: [ + frame({ + function: "resolvePlan", + context: { pre: ["const tier = account.tier"], line: "return catalog[tier].plan", post: ["}"] }, + }), + frame({ function: "dispatch", file: "node_modules/hono/dist/compose.js", in_app: false }), + frame({ function: "handle", file: "node_modules/hono/dist/handle.js", in_app: false }), + frame({ + function: "handleRenewal", + file: "src/routes/renewals.ts", + context: { pre: [], line: "await subscriptions.renew(id)", post: [] }, + }), + ], + missing: [], +} + +const missingMap: SymbolicatedStack = { + status: "missing_map", + frames: [], + missing: ["https://app.acme.dev/assets/index-Bx81.js"], +} + +const wireWith = (stack: SymbolicatedStack | null, raw: string) => + Schema.decodeSync(V2ErrorIssueDetail)({ + id: encodePublicId("iss", issueId), + object: "error_issue", + kind: "error", + fingerprint_hash: "1", + service_name: "web", + exception_type: "TypeError", + exception_message: "x is undefined", + error_label: "TypeError", + top_frame: "at Kc (index-Bx81.js:1:48213)", + workflow_state: "triage", + priority: 1, + severity: null, + severity_source: null, + source_ref: null, + assigned_actor: null, + lease_holder: null, + lease_expires_at: null, + claimed_at: null, + notes: null, + first_seen_at: "2026-10-01T10:00:00.000Z", + last_seen_at: "2026-10-01T11:44:00.000Z", + occurrence_count: 12, + resolved_at: null, + last_resolved_at: null, + last_regressed_at: null, + regression_count: 0, + resolved_versions: [], + snooze_until: null, + archived_at: null, + has_open_incident: false, + comment_count: 0, + open_pull_request_count: 0, + merged_pull_request_count: 0, + timeseries: [], + sample_traces: [], + incidents: [], + environments: [], + latest_stacktrace: raw, + latest_stack: stack, + }) + +const delivered = (model: Model, stack: SymbolicatedStack | null, raw: string): Model => + pageUpdate( + model, + Message.CompletedFetchDetail({ + key: model.detail.key ?? "", + result: Result.succeed(wireWith(stack, raw)), + }), + ).model + +const loadedWith = (stack: SymbolicatedStack | null, raw: string = RAW): Model => + delivered( + pageUpdate( + init({ issueId, search: {} }, context).model, + Message.CompletedResolveWindow({ window, nowMs: NOW, mode: "Load" }), + ).model, + stack, + raw, + ) + +const view = (model: Model, h: HtmlBuilder): Html => + Option.match(detailOf(model), { + onNone: () => h.div([], []), + onSome: (detail) => + exceptionPanel(h, model, detail.issue, detail.latestStacktrace, detail.latestStack), + }) + +describe("issue stack trace", () => { + test("a mapped stack opens on the top app frame's code, with library frames folded", () => { + scene( + { update: pageUpdate, view }, + given(loadedWith(resolved)), + expectView(text("Source mapped")).toExist(), + expectView(selector("#issue-stack-frame-0 [data-error-line]")).toExist(), + expectView(text("dispatch")).toBeAbsent(), + click(role("button", { name: "2 library frames" })), + expectView(text("dispatch")).toExist(), + expectView(selector("#issue-stack-frame-3")).toBeAbsent(), + click(role("button", { name: /handleRenewal/ })), + expectView(selector("#issue-stack-frame-3 [data-error-line]")).toExist(), + ) + }) + + test("Raw swaps the frames for the text the SDK sent, and back", () => { + scene( + { update: pageUpdate, view }, + given(loadedWith(resolved)), + expectView(text(/assets\/index-Bx81\.js:1:48213/)).toBeAbsent(), + click(role("button", { name: "Raw" })), + expectView(text(/assets\/index-Bx81\.js:1:48213/)).toExist(), + expectView(text("resolvePlan")).toBeAbsent(), + click(role("button", { name: "Raw" })), + expectView(text("resolvePlan")).toExist(), + ) + }) + + test("a stack with no map keeps the raw text and names the file to upload a map for", () => { + scene( + { update: pageUpdate, view }, + given(loadedWith(missingMap)), + expectView( + text(/Could not map https:\/\/app\.acme\.dev\/assets\/index-Bx81\.js to source/), + ).toExist(), + expectView(text("maple sourcemaps upload")).toExist(), + expectView(text("Full stack trace")).toExist(), + expectView(text("Source mapped")).toBeAbsent(), + ) + }) + + test("a partly mapped stack lists the files that did not map, in the page rather than a tooltip", () => { + const partial: SymbolicatedStack = { + ...resolved, + status: "partial", + missing: ["https://app.acme.dev/assets/vendor-9f.js"], + } + scene( + { update: pageUpdate, view }, + given(loadedWith(partial)), + expectView(text("Partly source mapped")).toExist(), + expectView(text("Not mapped to source: https://app.acme.dev/assets/vendor-9f.js")).toExist(), + ) + }) + + test("Raised at keeps the reported frame when the top app frame did not map", () => { + const topUnmapped: SymbolicatedStack = { + ...resolved, + status: "partial", + frames: [ + frame({ function: "Kc", file: "https://app.acme.dev/assets/index-Bx81.js", resolved: false }), + ...resolved.frames, + ], + missing: ["https://app.acme.dev/assets/index-Bx81.js"], + } + scene( + { update: pageUpdate, view }, + given(loadedWith(topUnmapped)), + expectView(text("at Kc (index-Bx81.js:1:48213)")).toExist(), + expectView(text(/resolvePlan \(src\/billing\/plan\.ts/)).toBeAbsent(), + ) + }) + + test("a different stack arriving resets the rows the reader flipped", () => { + const flipped = pageUpdate(loadedWith(resolved), Message.ToggledStackRow({ key: "frame-3" })).model + const raw = pageUpdate(flipped, Message.ToggledRawStack()).model + const same = delivered(raw, resolved, RAW) + const next = delivered( + raw, + resolved, + `${RAW}\n at Zt (https://app.acme.dev/assets/index-Qz07.js:1:9)`, + ) + expect([same.stackToggles, same.isShowingRawStack]).toEqual([["frame-3"], true]) + expect([next.stackToggles, next.isShowingRawStack]).toEqual([[], false]) + const remapped = delivered(raw, { ...resolved, status: "partial" }, RAW) + expect([remapped.stackToggles, remapped.isShowingRawStack]).toEqual([[], false]) + }) + + test("an API with no symbolicated stack shows the raw disclosure as before", () => { + scene( + { update: pageUpdate, view }, + given(loadedWith(null)), + expectView(text("Full stack trace")).toExist(), + expectView(text(/Could not map/)).toBeAbsent(), + expectView(role("button", { name: "Raw" })).toBeAbsent(), + ) + }) +}) diff --git a/apps/web/src/page/errors/issue/update.ts b/apps/web/src/page/errors/issue/update.ts index 0e6b45651b..4c84808e6c 100644 --- a/apps/web/src/page/errors/issue/update.ts +++ b/apps/web/src/page/errors/issue/update.ts @@ -2,7 +2,7 @@ import { keyed, runSteps, type Step as KitStep } from "../../kit/keyed-step" import { chartEnvHandlers } from "@maple/views/charts/chart-env" import type { RequestMode } from "@maple/views/data/keyed" import { type ErrorIssueId, ErrorIssuePullRequestId } from "@maple/domain/http" -import { Option, Result, Schema, String as Str } from "effect" +import { Array as Arr, Option, Result, Schema, String as Str } from "effect" import { formatWarehouseDateTime } from "@maple/query-engine" import { SETUP_CARD_ID } from "./model" import { AsyncData, Command } from "foldkit" @@ -256,6 +256,8 @@ export const init = ( grouping: Keyed.idle(), similar: Keyed.idle(), openSkippedFrames: [], + stackToggles: [], + isShowingRawStack: false, splittingHash: null, mergingIssueId: null, groupingError: null, @@ -420,6 +422,33 @@ const navigateSearch = (model: Model, search: Search): Return => ({ }), }) +/** The stack as sent and as mapped: a map uploaded since the last load changes the second alone. */ +const stackIdentityOf = (model: Model): string | null => + Option.match(detailOf(model), { + onNone: () => null, + onSome: (detail) => + Arr.join( + [ + detail.latestStacktrace ?? "", + detail.latestStack?.status ?? "", + ...Arr.map( + detail.latestStack?.frames ?? [], + (frame) => + `${frame.function ?? ""}@${frame.file ?? ""}:${frame.line ?? ""}:${frame.column ?? ""}`, + ), + ], + "\n", + ), + }) + +/** The new detail; rows flipped open or closed belong to the old stack, so a different one resets them. */ +const withDetail = (model: Model, detail: Model["detail"]): Model => { + const next = { ...model, detail } + return stackIdentityOf(next) === stackIdentityOf(model) + ? next + : { ...next, stackToggles: [], isShowingRawStack: false } +} + export const update = (model: Model, message: Message, context: PageContext): Return => Message.match(message, { CompletedResolveWindow: ({ window, nowMs, mode }) => @@ -429,7 +458,7 @@ export const update = (model: Model, message: Message, context: PageContext): Re ]), CompletedFetchSession: (answer) => ({ model: acceptGrants(model, context.orgId, answer) }), CompletedFetchDetail: ({ key, result }) => - runSteps(syncSelects({ ...model, detail: Keyed.accept(model.detail, key, result) }), [ + runSteps(syncSelects(withDetail(model, Keyed.accept(model.detail, key, result))), [ loadedReads(context), vcsStep(context), groupingReads(context, "Load"), @@ -476,6 +505,15 @@ export const update = (model: Model, message: Message, context: PageContext): Re ClickedRetryGrouping: () => retryGrouping(model, context, "grouping"), ClickedRetrySimilar: () => retryGrouping(model, context, "similar"), ToggledSkippedFrames: ({ fingerprintHash }) => toggledSkippedFrames(model, fingerprintHash), + ToggledStackRow: ({ key }) => ({ + model: { + ...model, + stackToggles: model.stackToggles.includes(key) + ? Arr.filter(model.stackToggles, (toggled) => toggled !== key) + : [...model.stackToggles, key], + }, + }), + ToggledRawStack: () => ({ model: { ...model, isShowingRawStack: !model.isShowingRawStack } }), ClickedSplitOut: ({ fingerprintHash }) => clickedSplitOut(model, fingerprintHash), CompletedSplitOut: ({ fingerprintHash, result }) => completedGroupingWrite( diff --git a/apps/web/src/page/errors/issue/view-grouping.ts b/apps/web/src/page/errors/issue/view-grouping.ts index 37e2912c3d..6d498a0d5b 100644 --- a/apps/web/src/page/errors/issue/view-grouping.ts +++ b/apps/web/src/page/errors/issue/view-grouping.ts @@ -76,6 +76,10 @@ export const ruleLabel = (fingerprint: Fingerprint): string => { } case "frames": return "Generic type, keyed on frames" + case "source-mapped": + return "Same source-mapped frames" + case "source-mapped-function": + return "Same type, first source-mapped function" } } diff --git a/apps/web/src/page/errors/issue/view-overview.ts b/apps/web/src/page/errors/issue/view-overview.ts index f13441e1a3..08701d66b6 100644 --- a/apps/web/src/page/errors/issue/view-overview.ts +++ b/apps/web/src/page/errors/issue/view-overview.ts @@ -13,9 +13,15 @@ import { Message } from "./message" import type { Model } from "./model" import { typography } from "@maple/views/ui/typography" import { hstack, vstack } from "@maple/views/ui/stack" -import { Array as Arr, String as Str } from "effect" +import { Array as Arr, Option, String as Str } from "effect" import { stripClass } from "@maple/views/ui/rule" -import { disclosureStrip } from "../../kit/disclosure-strip" +import { disclosureStrip, monospaceBlock } from "../../kit/disclosure-strip" +import type { SymbolicatedStack } from "@maple/domain/errors/js-stack" +import { badge } from "@maple/views/ui/display" +import { icon } from "@maple/views/ui/icon" +import { inlineCode } from "@maple/views/ui/inline-code" +import { stackFrameList } from "@maple/views/ui/stack-frames" +import { toggle } from "@maple/views/ui/toggle" // `IssueExceptionPanel` and `IssueStats`: what broke, then how often and since when. @@ -38,14 +44,26 @@ export const issueField = (h: H, label: string, children: ReadonlyArray): const COPY_CLASS = "-my-0.5 shrink-0 opacity-0 transition-opacity focus-visible:opacity-100 group-hover/mono:opacity-100 pointer-coarse:opacity-100" +/** The top in-app frame as `function (file:line:column)`, when a map resolved that frame itself. */ +const mappedTopFrame = (stack: SymbolicatedStack | null): string | undefined => { + if (stack === null) return undefined + const frame = Option.getOrUndefined(Arr.findFirst(stack.frames, (f) => f.in_app)) + if (frame === undefined || !frame.resolved || frame.file === null) return undefined + const position = + frame.line === null ? "" : `:${frame.line}${frame.column === null ? "" : `:${frame.column}`}` + return `${frame.function ?? ""} (${frame.file}${position})` +} + /** The exception message, the top frame it was raised from, and the newest full stack trace. */ export const exceptionPanel = ( h: H, model: Model, issue: ErrorIssueDocument, stacktrace: string | null, + stack: SymbolicatedStack | null, ): Html => { const message = stripAnsi(issue.exceptionMessage || issue.errorLabel) + const topFrame = mappedTopFrame(stack) ?? issue.topFrame return panel(h, { className: "shrink-0 overflow-hidden" }, [ panelHeader(h, { title: "What broke", @@ -64,7 +82,7 @@ export const exceptionPanel = ( "This error carries no message, only its type and where it was raised.", ]), issueField(h, "Raised at", [ - issue.topFrame + topFrame ? hstack(h, { gap: "1.5", align: "start", shrink: true, className: "group/mono" }, [ h.code( [ @@ -72,11 +90,11 @@ export const exceptionPanel = ( "min-w-0 break-words font-mono text-xs leading-5 text-foreground-soft", ), ], - breakablePath(h, issue.topFrame), + breakablePath(h, topFrame), ), CopyButton.view(h, { model: model.fingerprintCopy, - value: issue.topFrame, + value: topFrame, label: "top frame", toParentMessage: (message) => Message.GotFingerprintCopyMessage({ message }), className: COPY_CLASS, @@ -86,13 +104,106 @@ export const exceptionPanel = ( "No stack frame was attributed to this fingerprint", ]), ]), + ...missingMapHint(h, stack), ]), - ...(stacktrace === null - ? [] - : [disclosureStrip(h, { label: "Full stack trace", text: stripAnsi(stacktrace) })]), + ...stackFoot(h, model, stacktrace, stack), ]) } +const rawStrip = (h: H, stacktrace: string | null): ReadonlyArray => + stacktrace === null + ? [] + : [disclosureStrip(h, { label: "Full stack trace", text: stripAnsi(stacktrace) })] + +/** Where to start when nothing mapped: the first minified file that did not map to source. */ +const missingMapHint = (h: H, stack: SymbolicatedStack | null): ReadonlyArray => { + const file = stack?.status === "missing_map" ? stack.missing[0] : undefined + return file === undefined + ? [] + : [ + typography(h, { size: "xs", tone: "muted", as: "p", className: "break-all" }, [ + `Could not map ${file} to source. Upload this build's maps with `, + inlineCode(h, {}, ["maple sourcemaps upload"]), + ", or check the uploaded map matches the build.", + ]), + ] +} + +/** The symbolicated frames under a "Source mapped" bar, with "Raw" swapping in the text as sent. */ +const symbolicatedStrip = (h: H, model: Model, stacktrace: string | null, stack: SymbolicatedStack): Html => + h.div( + [h.Class("border-t")], + [ + hstack(h, { gap: "2", justify: "between", className: "px-4 py-2" }, [ + hstack(h, { gap: "2", shrink: true }, [ + typography(h, { size: "xs", tone: "muted" }, ["Stack trace"]), + badge( + h, + { + variant: stack.status === "resolved" ? "ok" : "meta", + size: "sm", + }, + stack.status === "resolved" + ? [icon(h, "CircleCheckIcon", {}), "Source mapped"] + : ["Partly source mapped"], + ), + ]), + ...(stacktrace === null + ? [] + : [ + toggle( + h, + { + isPressed: model.isShowingRawStack, + onClick: Message.ToggledRawStack(), + size: "xs", + variant: "outline", + }, + ["Raw"], + ), + ]), + ]), + ...(stack.status === "partial" && stack.missing.length > 0 + ? [ + typography( + h, + { size: "xs", tone: "muted", as: "p", className: "break-all border-t px-4 py-2" }, + [`Not mapped to source: ${Arr.join(stack.missing, ", ")}`], + ), + ] + : []), + model.isShowingRawStack && stacktrace !== null + ? monospaceBlock(h, stripAnsi(stacktrace)) + : stackFrameList(h, { + frames: stack.frames, + toggled: model.stackToggles, + onToggle: (key) => Message.ToggledStackRow({ key }), + idPrefix: "issue-stack", + className: "border-t", + }), + ], + ) + +/** The panel's foot: mapped frames once a map matched, else today's raw strip. */ +const stackFoot = ( + h: H, + model: Model, + stacktrace: string | null, + stack: SymbolicatedStack | null, +): ReadonlyArray => { + if (stack === null) return rawStrip(h, stacktrace) + switch (stack.status) { + case "resolved": + case "partial": + return stack.frames.length === 0 + ? rawStrip(h, stacktrace) + : [symbolicatedStrip(h, model, stacktrace, stack)] + case "missing_map": + case "not_applicable": + return rawStrip(h, stacktrace) + } +} + /** The rail tone of a severity: high and critical read as critical, unset as neutral. */ const SEVERITY_STAT_TONE = { critical: "crit", diff --git a/apps/web/src/page/errors/issue/view.ts b/apps/web/src/page/errors/issue/view.ts index 192c5b8a76..dc2b62e452 100644 --- a/apps/web/src/page/errors/issue/view.ts +++ b/apps/web/src/page/errors/issue/view.ts @@ -234,7 +234,7 @@ const overview = ( ...relatedAnomaliesSection(h, relatedAnomaliesOf(model), clock), ] : [ - exceptionPanel(h, model, issue, detail.latestStacktrace), + exceptionPanel(h, model, issue, detail.latestStacktrace, detail.latestStack), // How often and since when, over the window's bars: one panel, read top to bottom. panel(h, { className: "shrink-0 overflow-hidden" }, [ issueStats(h, issue, statInputs, { isFlush: true }), diff --git a/apps/web/src/page/kit/disclosure-strip.ts b/apps/web/src/page/kit/disclosure-strip.ts index 427d60615f..3956405bec 100644 --- a/apps/web/src/page/kit/disclosure-strip.ts +++ b/apps/web/src/page/kit/disclosure-strip.ts @@ -28,13 +28,17 @@ export const disclosureStrip = ( options.label, ], ), - h.pre( - [ - h.Class( - "max-h-72 overflow-auto border-t bg-surface-sunken px-4 pt-3 pb-8 [mask-image:linear-gradient(to_bottom,black_80%,transparent)] font-mono text-xs leading-5 whitespace-pre-wrap break-words text-foreground-soft", - ), - ], - [options.text], + monospaceBlock(h, options.text), + ], + ) + +/** The strip's open block on its own: a capped, scrolling run of monospace text on the sunken wash. */ +export const monospaceBlock = (h: HtmlBuilder, text: string): Html => + h.pre( + [ + h.Class( + "max-h-72 overflow-auto border-t bg-surface-sunken px-4 pt-3 pb-8 [mask-image:linear-gradient(to_bottom,black_80%,transparent)] font-mono text-xs leading-5 whitespace-pre-wrap break-words text-foreground-soft", ), ], + [text], ) diff --git a/apps/web/src/page/settings/audit-log/icons.ts b/apps/web/src/page/settings/audit-log/icons.ts index f79aca71ab..acd10e4e02 100644 --- a/apps/web/src/page/settings/audit-log/icons.ts +++ b/apps/web/src/page/settings/audit-log/icons.ts @@ -67,6 +67,7 @@ const VERB_ICONS = { cancelled: "SquareIcon", ended: "SquareIcon", rolled: "ArrowRotateClockwiseIcon", + uploaded: "UploadIcon", rotated: "ArrowRotateClockwiseIcon", break_glass_rotated: "ArrowRotateClockwiseIcon", custom_domain_set: "GlobeIcon", diff --git a/apps/web/src/platform/service-identity.ts b/apps/web/src/platform/service-identity.ts new file mode 100644 index 0000000000..cceace42a8 --- /dev/null +++ b/apps/web/src/platform/service-identity.ts @@ -0,0 +1,5 @@ +/** + * The `service.name` the dashboard's browser telemetry reports. The deploy uploads its source maps + * under the same name (`alchemy.run.ts`), so error stacks match them by service and release. + */ +export const WEB_SERVICE_NAME = "maple-web" diff --git a/apps/web/src/platform/telemetry.ts b/apps/web/src/platform/telemetry.ts index f89a591b89..a18d1deb49 100644 --- a/apps/web/src/platform/telemetry.ts +++ b/apps/web/src/platform/telemetry.ts @@ -1,6 +1,7 @@ import { MapleFoldkit } from "@maple-dev/effect-sdk/foldkit" import { ANTICIPATED_ERROR_IDENTIFIERS } from "@maple/domain/anticipated-errors" import { selfIngestUrl } from "./ingest-url" +import { WEB_SERVICE_NAME } from "./service-identity" import { Option } from "effect" import { fromString } from "foldkit/url" import { urlToAppRoute } from "../route" @@ -19,7 +20,7 @@ const routeName = (pathname: string): string => * `maple.web.app` names the frontend that sent it. */ const maple = MapleFoldkit.make({ - serviceName: "maple-web", + serviceName: WEB_SERVICE_NAME, endpoint: selfIngestUrl, ingestKey: import.meta.env.VITE_MAPLE_INGEST_KEY, // The stage's name (`production`, `pr-`, `development`); a preview build's MODE is `production` too. diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index b523992152..3a12c91910 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -6,6 +6,8 @@ import { defineConfig, loadEnv, type Plugin } from "vite" import { siblingUrl } from "../../packages/infra/src/dev-urls.ts" import { clerkJsUrl } from "../../packages/domain/src/clerk-js-url.ts" import { versionManifest } from "./vite-plugin-version-manifest.ts" +import { mapleSourceMaps } from "../../packages/alchemy-maple/src/Vite.ts" +import { WEB_SOURCE_MAPS_DIR } from "./source-maps-dir.ts" const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.String)) @@ -141,6 +143,9 @@ export default defineConfig(({ mode, command }) => { // `/version.json`, which open tabs poll to offer a reload after a deploy (shell/version.ts). versionManifest(process.env.VITE_COMMIT_SHA?.trim() || ""), earlyBoot(), + // Hidden maps with debug ids, moved out of the served client into `.maple/` for the + // deploy to upload (`alchemy.run.ts`). Build only. + mapleSourceMaps({ mapsDir: path.resolve(import.meta.dirname, "..", "..", WEB_SOURCE_MAPS_DIR) }), ...(Str.toLowerCase(process.env.VITE_MAPLE_AUTH_MODE?.trim()) === "clerk" && clerkKey ? [clerkEarlyLoad(clerkKey)] : []), diff --git a/bun.lock b/bun.lock index d18c636f9b..0e337c68ea 100644 --- a/bun.lock +++ b/bun.lock @@ -170,6 +170,7 @@ "@maple/local-server": "workspace:*", "@maple/promql": "workspace:*", "@maple/query-engine": "workspace:*", + "@maple/sourcemaps": "workspace:*", "effect": "catalog:effect", }, "devDependencies": { @@ -615,24 +616,32 @@ "devDependencies": { "@alchemy.run/test": "catalog:alchemy", "@effect/platform-bun": "catalog:effect", + "@effect/platform-node": "catalog:effect", "@effect/vitest": "catalog:effect", + "@jridgewell/trace-mapping": "0.3.31", "@maple/domain": "workspace:*", "@maple/local-server": "workspace:*", + "@maple/sourcemaps": "workspace:*", "@types/bun": "^1.4.5", "@types/node": "catalog:tooling", "alchemy": "catalog:alchemy", "effect": "catalog:effect", "tsdown": "^0.23.7", "typescript": "catalog:tooling", + "vite": "catalog:", "vitest": "catalog:", }, "peerDependencies": { "@effect/platform-bun": "^4.0.0", + "@effect/platform-node": "^4.0.0", "alchemy": ">=2.0.0-beta.80 <3", "effect": "^4.0.0", + "vite": ">=6.0.0", }, "optionalPeers": [ "@effect/platform-bun", + "@effect/platform-node", + "vite", ], }, "packages/alerting-core": { @@ -679,6 +688,7 @@ "@distilled.cloud/planetscale": "1.0.0-rc.20", "@distilled.cloud/supabase": "1.0.0-rc.20", "@distilled.cloud/vercel": "1.0.0-rc.20", + "@jridgewell/trace-mapping": "0.3.31", "@maple-dev/effect-clickhouse-http": "workspace:*", "@maple-dev/effect-orm": "0.10.0", "@maple/alerting-core": "workspace:*", @@ -833,6 +843,7 @@ "@maple/primitives": "workspace:*", "@maple/query-model": "workspace:*", "@maple/security-audit": "workspace:*", + "@maple/sourcemaps": "workspace:*", "@maple/strings": "workspace:*", "@maple/widgets": "workspace:*", "effect": "catalog:effect", @@ -1033,6 +1044,16 @@ "vitest": "catalog:", }, }, + "packages/sourcemaps": { + "name": "@maple/sourcemaps", + "dependencies": { + "effect": "catalog:effect", + }, + "devDependencies": { + "@types/node": "catalog:tooling", + "typescript": "catalog:tooling", + }, + }, "packages/status-page": { "name": "@maple/status-page", "dependencies": { @@ -1636,6 +1657,8 @@ "@maple/security-audit": ["@maple/security-audit@workspace:packages/security-audit"], + "@maple/sourcemaps": ["@maple/sourcemaps@workspace:packages/sourcemaps"], + "@maple/status": ["@maple/status@workspace:apps/status"], "@maple/status-page": ["@maple/status-page@workspace:packages/status-page"], diff --git a/docs/api-v2.md b/docs/api-v2.md index 9fe614a520..97e7fbd52e 100644 --- a/docs/api-v2.md +++ b/docs/api-v2.md @@ -50,7 +50,7 @@ POST /v2/traces/search complex reads are POST .../search Every v2 object has a prefixed public ID (`key_4CzLmR…`, `dash_…`, `alrt_…`). Public IDs are opaque; internally they are a reversible base58 encoding of the internal ID, computed at the API boundary in `packages/domain/src/http/v2/public-id.ts`, which also holds the prefix registry (`PublicIdPrefixes`, the source of truth). No database migration: rows keep their raw UUIDs / internal strings. -Prefixes: `key` (API key), `ingk` (ingest key), `dash` (dashboard), `dbv` (dashboard version), `dshr` (dashboard share), `dtpl` (dashboard template), `alrt` (alert rule), `dest` (alert destination), `inc` (alert incident), `evt` (alert delivery event), `actor` (actor), `alog` (audit log entry), `einc` (error incident), `iss` (error issue), `inv` (investigation), `anom` (anomaly incident), `scrp` (scrape target), `upm` (uptime monitor), `stp` (status page), `stc` (status page component), `sti` (status page incident), `stu` (status page incident update), `rec` (recommendation), `amap` (attribute mapping), `srep` (session replay), `mdev` (mobile device), `chatw` (chat workspace), `afb` (agent feedback), `gcpc` (Google Cloud connector), `mcpc` (MCP OAuth connection), `dcred` (device credential), `dsrc` (data source), and `log` (synthetic log identity); `we` is reserved for webhooks. +Prefixes: `key` (API key), `ingk` (ingest key), `dash` (dashboard), `dbv` (dashboard version), `dshr` (dashboard share), `dtpl` (dashboard template), `alrt` (alert rule), `dest` (alert destination), `inc` (alert incident), `evt` (alert delivery event), `actor` (actor), `alog` (audit log entry), `einc` (error incident), `iss` (error issue), `inv` (investigation), `anom` (anomaly incident), `scrp` (scrape target), `upm` (uptime monitor), `stp` (status page), `stc` (status page component), `sti` (status page incident), `stu` (status page incident update), `rec` (recommendation), `amap` (attribute mapping), `srep` (session replay), `mdev` (mobile device), `chatw` (chat workspace), `afb` (agent feedback), `gcpc` (Google Cloud connector), `mcpc` (MCP OAuth connection), `dcred` (device credential), `dsrc` (data source), `smap` (source map file), and `log` (synthetic log identity); `we` is reserved for webhooks. Exception: Clerk-issued `org_…` / `user_…` IDs are already prefixed public IDs and pass through unchanged. diff --git a/docs/error-issue-lifecycle.md b/docs/error-issue-lifecycle.md index e08ec35941..515263b49c 100644 --- a/docs/error-issue-lifecycle.md +++ b/docs/error-issue-lifecycle.md @@ -279,6 +279,21 @@ loop in verification without a human ever seeing it. two weeks of production errors from 32 orgs, blind-labelled: issues fell 9.7% and 8.9%, and 91% of the merges it adds are one bug. Keying on a cause chain's root type and keeping the first named caller for every error were measured too and lowered F1, so they are not in it. + A minified browser bundle renames functions and content-hashed files every deploy, so where the + host binds the source map bucket, a key that reads frames (`frames`, `type-function`) is computed + from the stack mapped through the org's source maps instead: the in-app frames' original file and + function, never a line or column (rule `source-mapped`). A frame with no recovered function name + reads as its file plus its original source line's text (ends trimmed, inner text verbatim, so a + formatting-only edit of the throw line can split the issue); one with neither keeps the raw key, so two + throw sites in one file never share a key on the file alone. A stack that maps nothing keys exactly + as before, and every rule above frames (custom keys, org rules, chunk loads, type and message) + keeps its priority. Whether the org has any map is part of `config_digest`, so its first upload + re-keys its keys once; a sample whose build registered debug ids waits for its map (one hour from + first sighting) even before the org has any. Known limit: in an org that already has maps, a hash + whose map arrives after that hour keeps the raw key it was given; uploads do not re-key it, so + it joins its release's mapped issue only if that key matches. Upload maps in the deploy step. + A stored key is never replaced while its map is pending, its lookup failed, or the mapped stack + gives no identity (no name, no source text); an unmapped throw site never keys on its callers. - **Org grouping rules and detaching.** An org can add rules without a deploy (`packages/domain/src/tinybird/grouping-rules.ts`, `PUT /grouping-rules`, needs `error_policy:manage`): `merge` joins every error matching its globs into one issue per service, diff --git a/packages/alchemy-maple/README.md b/packages/alchemy-maple/README.md index 7590507c8b..e1d17f8644 100644 --- a/packages/alchemy-maple/README.md +++ b/packages/alchemy-maple/README.md @@ -113,6 +113,7 @@ seam when constructing the API client without the Alchemy provider collection. | `Maple.UptimeMonitor` | Create / update / delete. Props are the `POST /v2/uptime_monitors` body; the kind is `config.type`, and changing it replaces the monitor. Outputs `monitorId`, `heartbeatUrl`. | | `Maple.StatusPage` | Create / update / delete through the page's config document, plus `password` and `custom_domain`. Components keep their IDs by name; an unset `manual_status` leaves a responder's override alone. Outputs `statusPageId`, `components`, `customDomain.dnsRecords`. | | `Maple.IngestKeys` | Read-only per-org singleton. Surfaces `publicKey` / `privateKey` as `Redacted` outputs; delete only stops tracking it. | +| `Maple.SourceMaps` | Uploads a build's JavaScript source maps (see below). Re-uploads only when the maps, service, release or prefix changed. Deleting it deletes nothing: older releases still need their maps, and Maple removes maps unused for 90 days. Needs `source_maps:write`. | ## Typed dashboard data @@ -203,6 +204,46 @@ Cloudflare options, forwarded unchanged. Full docs: [maple.dev/docs/iac/alchemy](https://maple.dev/docs/iac/alchemy). +## Source maps + +`@maple-dev/alchemy/vite` gives each built JS file a debug id and moves its source maps out of the +deployed output (`.maple/sourcemaps/` by default), so they are never served. `Maple.SourceMaps` +uploads them after the build, so error stacks in Maple show your original source. + +```typescript +// vite.config.ts +import { mapleSourceMaps } from "@maple-dev/alchemy/vite" + +export default defineConfig({ plugins: [mapleSourceMaps()] }) +``` + +```typescript +// alchemy.run.ts +Effect.gen(function* () { + const web = yield* Cloudflare.Website.Vite("web") + yield* Maple.SourceMaps("web-sourcemaps", { + dir: ".maple/sourcemaps/client", + service: "web", // the service.name the app reports + release: process.env.GITHUB_SHA, // its service.version: matches maps without a debug id + after: web.hash, // upload after the build, and re-check when it changes + matchBy: "release", // telemetry without debug ids: see below + }) +}) +``` + +Set `matchBy: "release"` when your telemetry reports no debug ids (Maple's SDKs other than +`@maple-dev/browser`): maps then upload without them, matched by `service`, `release` and path, so +a chunk two releases share keeps a map under each. The default, `"debugId"`, suits `@maple-dev/browser`. + +The first upload happens on the first deploy that runs the build after you add the plugin; a +redeploy that skips an unchanged build finds no maps and logs a warning. On that first deploy, a +chunk whose hashed name is unchanged gets new contents (the snippet goes in after Rollup names it), +so a browser or CDN that cached it may serve the old copy for that one release; later builds are +deterministic. + +The plugin runs in Node and needs `@effect/platform-node`. `dir` can also be any build output where +each JS file has its map beside it, as `maple sourcemaps upload` reads it. + ## Local development `Local` runs Maple Local inside `alchemy dev`: an embedded OTLP collector, query API and diff --git a/packages/alchemy-maple/package.json b/packages/alchemy-maple/package.json index 18911322c1..c8edef75ff 100644 --- a/packages/alchemy-maple/package.json +++ b/packages/alchemy-maple/package.json @@ -41,6 +41,10 @@ "./local-sidecar": { "types": "./dist/local-sidecar.d.mts", "import": "./dist/local-sidecar.mjs" + }, + "./vite": { + "types": "./dist/vite.d.mts", + "import": "./dist/vite.mjs" } }, "publishConfig": { @@ -58,25 +62,37 @@ "devDependencies": { "@alchemy.run/test": "catalog:alchemy", "@effect/platform-bun": "catalog:effect", + "@effect/platform-node": "catalog:effect", "@effect/vitest": "catalog:effect", + "@jridgewell/trace-mapping": "0.3.31", "@maple/domain": "workspace:*", "@maple/local-server": "workspace:*", + "@maple/sourcemaps": "workspace:*", "@types/bun": "^1.4.5", "@types/node": "catalog:tooling", "alchemy": "catalog:alchemy", "effect": "catalog:effect", "tsdown": "^0.23.7", "typescript": "catalog:tooling", + "vite": "catalog:", "vitest": "catalog:" }, "peerDependencies": { "@effect/platform-bun": "^4.0.0", + "@effect/platform-node": "^4.0.0", "alchemy": ">=2.0.0-beta.80 <3", - "effect": "^4.0.0" + "effect": "^4.0.0", + "vite": ">=6.0.0" }, "peerDependenciesMeta": { "@effect/platform-bun": { "optional": true + }, + "@effect/platform-node": { + "optional": true + }, + "vite": { + "optional": true } } } diff --git a/packages/alchemy-maple/src/MapleApi.ts b/packages/alchemy-maple/src/MapleApi.ts index ccffa44721..bc34cc620f 100644 --- a/packages/alchemy-maple/src/MapleApi.ts +++ b/packages/alchemy-maple/src/MapleApi.ts @@ -39,6 +39,12 @@ export interface MapleApiContract { readonly patch: (path: string, body: unknown) => Effect.Effect readonly put: (path: string, body: unknown) => Effect.Effect readonly delete: (path: string) => Effect.Effect + /** POSTs raw bytes (a file upload) as the body; `path` carries any query string. */ + readonly upload: ( + path: string, + body: Uint8Array, + contentType: string, + ) => Effect.Effect } export class MapleApi extends Context.Service()("Maple::Api") {} @@ -134,7 +140,12 @@ export const make = Effect.gen(function* () { const { baseUrl, apiKey } = yield* MapleEnvironment const httpClient = yield* HttpClient.HttpClient - const request = (method: "GET" | "POST" | "PATCH" | "PUT" | "DELETE", path: string, body?: unknown) => { + const request = ( + method: "GET" | "POST" | "PATCH" | "PUT" | "DELETE", + path: string, + body?: unknown, + raw?: { readonly bytes: Uint8Array; readonly contentType: string }, + ) => { const canAutomaticallyRetry = method === "GET" || method === "DELETE" const execute: (attempt: number) => Effect.Effect = Effect.fn( "MapleApi.requestAttempt", @@ -146,7 +157,9 @@ export const make = Effect.gen(function* () { Accept: "application/json", }), ) - if (body !== undefined) { + if (raw !== undefined) { + req = HttpClientRequest.bodyUint8Array(req, raw.bytes, raw.contentType) + } else if (body !== undefined) { req = yield* HttpClientRequest.bodyJson(req, body).pipe( Effect.mapError( (error) => @@ -212,6 +225,8 @@ export const make = Effect.gen(function* () { patch: (path: string, body: unknown) => request("PATCH", path, body), put: (path: string, body: unknown) => request("PUT", path, body), delete: (path: string) => request("DELETE", path), + upload: (path: string, bytes: Uint8Array, contentType: string) => + request("POST", path, undefined, { bytes, contentType }), } }) diff --git a/packages/alchemy-maple/src/Providers.ts b/packages/alchemy-maple/src/Providers.ts index 9a348016a0..96d3a1f309 100644 --- a/packages/alchemy-maple/src/Providers.ts +++ b/packages/alchemy-maple/src/Providers.ts @@ -8,6 +8,7 @@ import { Dashboard, DashboardProvider } from "./Dashboard" import { IngestKeys, IngestKeysProvider } from "./IngestKeys" import { MapleApiFromHttpClient } from "./MapleApi" import * as MapleEnvironment from "./MapleEnvironment" +import { SourceMaps, SourceMapsProvider } from "./SourceMaps" import { StatusPage, StatusPageProvider } from "./StatusPage" import { UptimeMonitor, UptimeMonitorProvider } from "./UptimeMonitor" @@ -25,7 +26,8 @@ export class Providers extends Provider.ProviderCollection()("Maple") * * Credentials come from `MAPLE_API_KEY` / `MAPLE_API_URL` and requests use the * runtime's global `fetch`. Use {@link providersWithDependencies} to supply a - * different environment or HTTP client. + * different environment or HTTP client. `Maple.SourceMaps` reads files through the stack's + * `FileSystem` and `Path`, which Alchemy supplies. */ export const providers = () => providersWithDependencies().pipe( @@ -59,6 +61,7 @@ export const providersWithDependencies = () => IngestKeys, UptimeMonitor, StatusPage, + SourceMaps, ]), ).pipe( Layer.provide( @@ -70,6 +73,7 @@ export const providersWithDependencies = () => IngestKeysProvider(), UptimeMonitorProvider(), StatusPageProvider(), + SourceMapsProvider(), ), ), Layer.provide(MapleApiFromHttpClient()), diff --git a/packages/alchemy-maple/src/SourceMaps.ts b/packages/alchemy-maple/src/SourceMaps.ts new file mode 100644 index 0000000000..011d1b5e7b --- /dev/null +++ b/packages/alchemy-maple/src/SourceMaps.ts @@ -0,0 +1,297 @@ +// BOUNDARY-FILE: This module reads source map files and a manifest from disk before upload. +import { createHash } from "node:crypto" +import { SOURCE_MAP_MAX_BYTES } from "@maple/sourcemaps/limits" +import { + existingDebugId, + findJsFiles, + isIndexMap, + MANIFEST_FILE, + mapDebugId, + mapUsers, + SourceMapsManifest, +} from "@maple/sourcemaps" +import { Array as Arr, Effect, Option, Order, Result, Schema, String as Str } from "effect" +import { FileSystem } from "effect/FileSystem" +import { Path } from "effect/Path" +import { isResolved } from "alchemy/Diff" +import * as Provider from "alchemy/Provider" +import { Resource } from "alchemy/Resource" +import { MapleSourceMapsReadError } from "./errors" +import { MapleApi } from "./MapleApi" +import type { Providers } from "./Providers" + +export interface SourceMapsProps { + /** + * The directory holding the maps: the Vite plugin's `mapsDir` (with its manifest), or any + * build output where each JS file has its map beside it. + */ + dir: string + /** The service the code reports as (OTel `service.name`). */ + service: string + /** + * The release it reports (OTel `service.version`). Maps without a debug id are matched by + * service, release and path, so they are skipped without one. + */ + release?: string + /** The path the files are served under, prepended to each file path, e.g. `static/`. */ + urlPrefix?: string + /** + * Any value from the build this follows, such as a Worker's asset hash: it orders the upload + * after the build and re-checks the maps when the build changes. Not uploaded. + */ + after?: unknown + /** + * How stacks find these maps. `"debugId"` (default) uploads each map under the debug id its file + * registers, for SDKs that report debug ids. `"release"` uploads without them, matched by service, + * release and path: for telemetry that sends no debug ids, where a chunk shared by two releases + * would otherwise keep one row under one release. Needs `release`. + */ + matchBy?: "debugId" | "release" +} + +export type SourceMaps = Resource< + "Maple.SourceMaps", + SourceMapsProps, + { + /** Maps uploaded by the last reconcile that found changed maps. */ + uploaded: number + /** The debug ids among them. */ + debugIds: ReadonlyArray + /** A digest of the maps and the props they were uploaded under; unchanged, nothing uploads. */ + digest: string + }, + never, + Providers +> + +/** + * Uploads a build's JavaScript source maps to Maple so error stacks show original source. Runs + * after the build, and uploads again only when the maps (or service, release or prefix) changed. + * Needs an API key with `source_maps:write`. + * + * Deleting it uploads nothing and deletes nothing on purpose: errors from earlier releases still + * need their maps, and the server deletes maps no stack has used for 90 days. + * + * @example + * ```typescript + * const web = yield* Cloudflare.Website.Vite("web") + * yield* Maple.SourceMaps("web-sourcemaps", { + * dir: ".maple/sourcemaps/client", + * service: "web", + * release: process.env.GITHUB_SHA, + * after: web.hash, + * }) + * ``` + */ +export const SourceMaps = Resource("Maple.SourceMaps") + +interface PlannedMap { + readonly minifiedPath: string + readonly debugId: Option.Option + readonly bytes: Uint8Array +} + +const decodeManifest = Schema.decodeUnknownEffect(Schema.fromJsonString(SourceMapsManifest)) + +/** The served path of a file below the deploy root, `urlPrefix` first, never with a leading slash. */ +export const minifiedPathFor = (urlPrefix: string | undefined, file: string): string => { + const prefix = urlPrefix ?? "" + const joined = prefix === "" || Str.endsWith("/")(prefix) ? `${prefix}${file}` : `${prefix}/${file}` + return Str.replace(/^(?:~\/|\/)+/, "")(joined) +} + +const sha256 = (data: Uint8Array | string) => createHash("sha256").update(data).digest("hex") + +/** Every map in `props.dir` with the path and debug id it uploads under; none when the dir is absent. */ +const planMaps = (props: SourceMapsProps) => + Effect.gen(function* () { + const fs = yield* FileSystem + const path = yield* Path + const readError = (cause: unknown) => + new MapleSourceMapsReadError({ + message: `Could not read source maps in ${props.dir}`, + path: props.dir, + cause, + }) + if (!(yield* fs.exists(props.dir).pipe(Effect.mapError(readError)))) return [] + const manifestPath = path.join(props.dir, MANIFEST_FILE) + if (yield* fs.exists(manifestPath).pipe(Effect.mapError(readError))) { + const manifest = yield* fs + .readFileString(manifestPath) + .pipe(Effect.flatMap(decodeManifest), Effect.mapError(readError)) + return yield* Effect.forEach(manifest.files, (entry) => + Effect.mapBoth(fs.readFile(path.join(props.dir, entry.map)), { + onFailure: readError, + onSuccess: (bytes): PlannedMap => ({ + minifiedPath: minifiedPathFor(props.urlPrefix, entry.file), + debugId: Option.fromNullishOr(entry.debugId), + bytes, + }), + }), + ) + } + // No manifest: maps beside their JS files, as `maple sourcemaps upload` reads them. + const files = yield* findJsFiles(props.dir).pipe(Effect.mapError(readError)) + const users = mapUsers(files) + return yield* Effect.forEach( + Arr.flatMap(files, (js) => + Option.toArray(Option.map(js.mapPath, (mapPath) => ({ js, mapPath }))), + ), + ({ js, mapPath }) => + Effect.mapBoth(fs.readFile(mapPath), { + onFailure: readError, + onSuccess: (bytes): PlannedMap => { + const shared = (users.get(mapPath) ?? 0) > 1 + return { + minifiedPath: minifiedPathFor(props.urlPrefix, js.file), + // The file's own id; a shared map's id belongs to no one file. + debugId: Option.orElse(existingDebugId(js.code), () => + shared ? Option.none() : mapDebugId(new TextDecoder().decode(bytes)), + ), + bytes, + } + }, + }), + ) + }) + +/** Changes when any map, its path or debug id, or the props it uploads under change. */ +export const sourceMapsDigest = (props: SourceMapsProps, maps: ReadonlyArray): string => + sha256( + Arr.join( + [ + props.service, + props.release ?? "", + props.urlPrefix ?? "", + props.matchBy ?? "debugId", + ...Arr.map( + Arr.sort( + maps, + Order.mapInput(Order.String, (map: PlannedMap) => map.minifiedPath), + ), + (map) => + Arr.join( + [map.minifiedPath, Option.getOrElse(map.debugId, () => ""), sha256(map.bytes)], + "\u0001", + ), + ), + ], + "\u0000", + ), + ) + +const byRelease = (props: SourceMapsProps) => props.matchBy === "release" +const hasRelease = (props: SourceMapsProps) => props.release !== undefined && props.release !== "" + +/** Why a map is not uploaded, or none when it is. */ +const skipReason = (props: SourceMapsProps, map: PlannedMap): Option.Option => { + if (map.bytes.byteLength > SOURCE_MAP_MAX_BYTES) return Option.some("it is over 10 MiB") + if (isIndexMap(new TextDecoder().decode(map.bytes))) + return Option.some("index source maps are not supported") + if (byRelease(props) && !hasRelease(props)) return Option.some('`matchBy: "release"` needs a release') + if (Option.isNone(map.debugId) && !hasRelease(props)) + return Option.some("it has no debug id and no release is set") + return Option.none() +} + +const uploadQuery = (props: SourceMapsProps, map: PlannedMap): string => { + const params: Array<[string, string]> = [ + ["minified_path", map.minifiedPath], + ["service", props.service], + ] + if (!byRelease(props) && Option.isSome(map.debugId)) params.push(["debug_id", map.debugId.value]) + if (hasRelease(props)) params.push(["version", props.release ?? ""]) + return new URLSearchParams(params).toString() +} + +const MapJson = Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)) +const decodeMapJson = Schema.decodeUnknownResult(MapJson) +const encodeMapJson = Schema.encodeResult(MapJson) + +/** + * The body to upload. Matched by release, the map's own `debugId` / `debug_id` go too, or the server + * would file it under that id and one release's upload would replace another's. + */ +const uploadBody = (props: SourceMapsProps, map: PlannedMap): Uint8Array => { + if (!byRelease(props)) return map.bytes + return Result.match( + Result.flatMap( + decodeMapJson(new TextDecoder().decode(map.bytes)), + ({ debugId: _a, debug_id: _b, ...rest }) => encodeMapJson(rest), + ), + { onFailure: () => map.bytes, onSuccess: (text) => new TextEncoder().encode(text) }, + ) +} + +export const SourceMapsProvider = () => + Provider.effect( + SourceMaps, + Effect.gen(function* () { + const api = yield* MapleApi + const platform = yield* Effect.context() + const plan = (props: SourceMapsProps) => + Effect.map(planMaps(props), (maps) => ({ maps, digest: sourceMapsDigest(props, maps) })).pipe( + Effect.provide(platform), + ) + // A redeploy of an unchanged build skips the bundler, so no maps were written this run. + const warnNoMaps = (props: SourceMapsProps) => + Effect.logWarning( + `No source maps in ${props.dir}: the build did not run in this deploy, so nothing was uploaded. The next deploy that builds uploads them.`, + ) + return { + // The maps on disk decide: a build that changed them updates, one that did not is a noop. + diff: Effect.fn(function* ({ news, output }) { + if (output === undefined || !isResolved(news)) return undefined + const planned = yield* plan(news) + if (planned.maps.length === 0) { + yield* warnNoMaps(news) + return { action: "noop" } as const + } + return planned.digest === output.digest + ? ({ action: "noop" } as const) + : ({ action: "update", stables: [] } as const) + }), + reconcile: Effect.fn(function* ({ news, output }) { + const planned = yield* plan(news) + // No maps here (a build that was skipped): keep what the last upload recorded. + if (planned.maps.length === 0) { + yield* warnNoMaps(news) + return output ?? { uploaded: 0, debugIds: [], digest: planned.digest } + } + if (output !== undefined && output.digest === planned.digest) return output + const sendable = yield* Effect.filter(planned.maps, (map) => + Option.match(skipReason(news, map), { + onNone: () => Effect.succeed(true), + onSome: (reason) => + Effect.as( + Effect.logWarning( + `Skipped the source map for ${map.minifiedPath}: ${reason}`, + ), + false, + ), + }), + ) + yield* Effect.forEach( + sendable, + (map) => + api.upload( + `/v2/source_maps?${uploadQuery(news, map)}`, + uploadBody(news, map), + "application/json", + ), + { concurrency: 4, discard: true }, + ) + yield* Effect.logInfo(`Uploaded ${sendable.length} source map(s) for ${news.service}`) + return { + uploaded: sendable.length, + debugIds: byRelease(news) + ? [] + : Arr.dedupe(Arr.getSomes(Arr.map(sendable, (map) => map.debugId))), + digest: planned.digest, + } + }), + // Earlier releases still need their maps; the server's retention removes unused ones. + delete: () => Effect.void, + } + }), + ) diff --git a/packages/alchemy-maple/src/Vite.ts b/packages/alchemy-maple/src/Vite.ts new file mode 100644 index 0000000000..2b8898031f --- /dev/null +++ b/packages/alchemy-maple/src/Vite.ts @@ -0,0 +1,113 @@ +/** + * `mapleSourceMaps()`: a Vite plugin that gives each built JS file a debug id, then moves its + * source maps out of the deployed output so they are never served. `Maple.SourceMaps` uploads + * them from there. + * + * @example + * ```typescript + * // vite.config.ts + * import { mapleSourceMaps } from "@maple-dev/alchemy/vite" + * + * export default defineConfig({ plugins: [mapleSourceMaps()] }) + * ``` + */ +import * as NodeServices from "@effect/platform-node/NodeServices" +import { injectDirectory, relocateMaps } from "@maple/sourcemaps" +import { Array as Arr } from "effect" +import * as Effect from "effect/Effect" +import { Path } from "effect/Path" +import type { Plugin } from "vite" + +export interface MapleSourceMapsOptions { + /** + * Where the maps go, outside the deployed output. Defaults to + * `/.maple/sourcemaps/`. + */ + readonly mapsDir?: string + /** + * The Vite environments whose output is processed. Defaults to `["client"]`: the browser + * bundle. A build without the environment API is always processed. + */ + readonly environments?: ReadonlyArray +} + +/** What one build did: the maps moved and the files the manifest lists. */ +export interface MapleSourceMapsResult { + readonly outDirs: ReadonlyArray + readonly mapsDir: string + readonly moved: number + readonly files: number +} + +/** Injects every output, then moves their maps to `mapsDir` under one manifest. */ +export const processBuildOutputs = (outDirs: ReadonlyArray, mapsDir: string) => + Effect.gen(function* () { + const outputs = yield* Effect.forEach(Arr.dedupe(outDirs), (outDir) => + Effect.map(injectDirectory(outDir, { dryRun: false }), (results) => ({ outDir, results })), + ) + const relocated = yield* relocateMaps(mapsDir, outputs) + return { + outDirs: Arr.map(outputs, (output) => output.outDir), + mapsDir, + moved: relocated.moved, + files: relocated.files.length, + } satisfies MapleSourceMapsResult + }) + +/** + * Requires source maps (`build.sourcemap` becomes `"hidden"` when unset or off, so no public + * `sourceMappingURL` comment is written). When a build finishes it injects debug ids into every + * output it wrote and moves each `.map` to `mapsDir` with a `maple-sourcemaps.json` manifest. Runs + * in Node; Bun is not required. + * + * The first deploy with the plugin changes chunk contents without changing their hashed names + * (the injection runs after Rollup names them), so a browser or CDN that cached a chunk from the + * build before may still serve it unshifted for that one release. Later builds are deterministic, + * so it does not recur. + */ +export const mapleSourceMaps = (options: MapleSourceMapsOptions = {}): Plugin => { + const environments = options.environments ?? ["client"] + let root = process.cwd() + // Output dirs written in the current build, per environment: several outputs may share a dir. + const written = new Map>() + // A build without the environment API (Vite 5) has no `environment` on its plugin context. + const environmentOf = (context: { readonly environment?: { readonly name: string } }) => + context.environment?.name + return { + name: "maple:source-maps", + apply: "build", + config: (config) => + config.build?.sourcemap === undefined || config.build.sourcemap === false + ? { build: { sourcemap: "hidden" } } + : undefined, + configResolved: (config) => { + root = config.root + }, + writeBundle(outputOptions) { + const environment = environmentOf(this) + if (environment !== undefined && !environments.includes(environment)) return + if (outputOptions.dir === undefined) return + const key = environment ?? "" + written.set(key, [...(written.get(key) ?? []), outputOptions.dir]) + }, + async closeBundle() { + const key = environmentOf(this) ?? "" + const dirs = written.get(key) ?? [] + written.delete(key) + if (dirs.length === 0) return + const program = Effect.gen(function* () { + const path = yield* Path + const outDirs = Arr.map(dirs, (dir) => path.resolve(root, dir)) + const mapsDir = + options.mapsDir === undefined + ? path.join(root, ".maple", "sourcemaps", path.basename(outDirs[0] ?? root)) + : path.resolve(root, options.mapsDir) + return yield* processBuildOutputs(outDirs, mapsDir) + }) + const result = await Effect.runPromise(program.pipe(Effect.provide(NodeServices.layer))) + this.info( + `moved ${result.moved} source map(s) to ${result.mapsDir}; ${result.files} file(s) carry a debug id`, + ) + }, + } +} diff --git a/packages/alchemy-maple/src/errors.ts b/packages/alchemy-maple/src/errors.ts index 59a1d13e53..56f1e43c05 100644 --- a/packages/alchemy-maple/src/errors.ts +++ b/packages/alchemy-maple/src/errors.ts @@ -128,6 +128,12 @@ export class MapleDashboardIdentityError extends Schema.TaggedError()( + "@maple/alchemy/errors/SourceMapsReadError", + { message: Schema.String, path: Schema.String, cause: Schema.Defect() }, +) {} + export type MapleClientError = | MapleApiRequestEncodingError | MapleApiTransportError diff --git a/packages/alchemy-maple/src/index.ts b/packages/alchemy-maple/src/index.ts index 182b7330c8..afc5c300cf 100644 --- a/packages/alchemy-maple/src/index.ts +++ b/packages/alchemy-maple/src/index.ts @@ -2,7 +2,7 @@ * Alchemy provider for Maple resources. * * Declare Maple API keys, ingest keys, dashboards, alert destinations, alert - * rules, uptime monitors and status pages in your `alchemy.run.ts`, authenticated with a `maple_ak_…` + * rules, uptime monitors, status pages and source map uploads in your `alchemy.run.ts`, authenticated with a `maple_ak_…` * API key against the Maple public v2 API. * * @example @@ -56,6 +56,7 @@ export { MapleAlertRuleOwnershipError, MapleAlertRuleTagsError, MapleDashboardIdentityError, + MapleSourceMapsReadError, MapleApiRequestEncodingError, MapleApiResponseDecodeError, MapleApiResponseReadError, @@ -75,6 +76,13 @@ export { IngestKeys, IngestKeysProvider, type IngestKeysProps } from "./IngestKe export { listAll, MapleApi, MapleApiFromHttpClient, MapleApiLive, type MapleApiContract } from "./MapleApi" export { DEFAULT_BASE_URL, fromEnv, MapleEnvironment } from "./MapleEnvironment" export { Providers, providers, providersWithDependencies } from "./Providers" +export { + minifiedPathFor, + SourceMaps, + SourceMapsProvider, + sourceMapsDigest, + type SourceMapsProps, +} from "./SourceMaps" export { StatusPage, StatusPageProvider, diff --git a/packages/alchemy-maple/test/engine.test.ts b/packages/alchemy-maple/test/engine.test.ts index 517d015b89..4dc4cd9040 100644 --- a/packages/alchemy-maple/test/engine.test.ts +++ b/packages/alchemy-maple/test/engine.test.ts @@ -120,6 +120,7 @@ const makeHarness = () => { else documents.delete(path) return Effect.void }), + upload: (path) => Effect.die(`unexpected upload ${path}`), } const providers = Layer.effect( Providers, diff --git a/packages/alchemy-maple/test/provider-layers.test.ts b/packages/alchemy-maple/test/provider-layers.test.ts index 5e634ce3a3..5a7a4c1fac 100644 --- a/packages/alchemy-maple/test/provider-layers.test.ts +++ b/packages/alchemy-maple/test/provider-layers.test.ts @@ -1,3 +1,4 @@ +import * as NodeServices from "@effect/platform-node/NodeServices" import { noopSession } from "alchemy/Report" import { ConfigProvider, Effect, Layer, Redacted, Record as Rec } from "effect" import { HttpClient, HttpClientResponse } from "effect/http" @@ -9,9 +10,11 @@ import { Providers, providers, providersWithDependencies } from "../src/Provider import { Stack } from "alchemy/Stack" import { Stage } from "alchemy/Stage" +// What Alchemy supplies a stack's providers: its identity and the platform's files and paths. const stackLayer = Layer.mergeAll( Layer.succeed(Stack, { name: "test", stage: "test", resources: {}, bindings: {}, actions: {} }), Layer.succeed(Stage, "test"), + NodeServices.layer, ) const session = noopSession @@ -115,6 +118,7 @@ describe("Maple provider layers", () => { "Maple.ApiKey", "Maple.Dashboard", "Maple.IngestKeys", + "Maple.SourceMaps", "Maple.StatusPage", "Maple.UptimeMonitor", ]) diff --git a/packages/alchemy-maple/test/providers.test.ts b/packages/alchemy-maple/test/providers.test.ts index 9dd8892919..1d3ed04832 100644 --- a/packages/alchemy-maple/test/providers.test.ts +++ b/packages/alchemy-maple/test/providers.test.ts @@ -41,6 +41,7 @@ const makeStub = ( patch: (path, body) => dispatch("PATCH", path, body), put: (path, body) => dispatch("PUT", path, body), delete: (path) => dispatch("DELETE", path), + upload: (path) => Effect.die(`unexpected upload ${path}`), }, } } diff --git a/packages/alchemy-maple/test/source-maps.test.ts b/packages/alchemy-maple/test/source-maps.test.ts new file mode 100644 index 0000000000..8d89a75a75 --- /dev/null +++ b/packages/alchemy-maple/test/source-maps.test.ts @@ -0,0 +1,219 @@ +import { describe, expect, it } from "@effect/vitest" +import * as NodeServices from "@effect/platform-node/NodeServices" +import * as Core from "@alchemy.run/test/Core" +import * as Provider from "alchemy/Provider" +import * as State from "alchemy/State" +import { Array as Arr, Effect, Layer, Option, Record as Rec, String as Str } from "effect" +import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { MapleApi, type MapleApiContract } from "../src/MapleApi" +import { Providers } from "../src/Providers" +import { SourceMaps, SourceMapsProvider } from "../src/SourceMaps" +import { processBuildOutputs } from "../src/Vite" +import { SourceMapsManifest } from "@maple/sourcemaps" +import { Schema } from "effect" + +const decodeManifest = Schema.decodeUnknownSync(Schema.fromJsonString(SourceMapsManifest)) +const decodeMap = Schema.decodeUnknownSync( + Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)), +) + +interface Upload { + readonly path: string + readonly query: Readonly> + readonly body: string + readonly contentType: string +} + +const makeHarness = () => { + const uploads: Array = [] + const unexpected = (method: string) => (path: string) => Effect.die(`unexpected ${method} ${path}`) + const api: MapleApiContract = { + get: unexpected("GET"), + post: unexpected("POST"), + patch: unexpected("PATCH"), + put: unexpected("PUT"), + delete: unexpected("DELETE"), + upload: (path, body, contentType) => + Effect.sync(() => { + const url = new URL(path, "https://maple.test") + uploads.push({ + path: url.pathname, + query: Rec.fromEntries(Arr.fromIterable(url.searchParams)), + body: new TextDecoder().decode(body), + contentType, + }) + return { object: "source_map", id: `smap_${uploads.length}` } + }), + } + const providers = Layer.effect(Providers, Provider.collection([SourceMaps])).pipe( + Layer.provide(SourceMapsProvider()), + Layer.provide(Layer.succeed(MapleApi, api)), + Layer.provide(NodeServices.layer), + ) + const options = { providers, state: State.inMemoryState(), stage: "test", adopt: false, dev: false } + return { + uploads, + stack: (name: string) => Core.scratchStack(options, name), + run: (effect: Core.TestEffect) => Core.toEffect(effect, options), + } +} + +const map = (source: string) => + JSON.stringify({ version: 3, sources: [source], names: [], mappings: "AAAA;AACA" }) + +/** A built output with two JS files and their maps, processed as the Vite plugin does. */ +const buildOutput = (root: string, secondSource = "src/b.ts") => + Effect.gen(function* () { + const dist = join(root, "dist") + mkdirSync(join(dist, "assets"), { recursive: true }) + writeFileSync(join(dist, "assets/a.js"), "a()\n") + writeFileSync(join(dist, "assets/a.js.map"), map("src/a.ts")) + writeFileSync(join(dist, "assets/b.js"), "b()\n") + writeFileSync(join(dist, "assets/b.js.map"), map(secondSource)) + return yield* processBuildOutputs([dist], join(root, "maps")).pipe(Effect.provide(NodeServices.layer)) + }) + +describe("Maple.SourceMaps", () => { + it.live("uploads each map once, and again only when the build changed", () => { + const h = makeHarness() + const stack = h.stack("source-maps") + const root = mkdtempSync(join(tmpdir(), "maple-maps-")) + const props = { dir: join(root, "maps"), service: "web", release: "abc123", urlPrefix: "static/" } + return h.run( + Effect.gen(function* () { + yield* buildOutput(root) + const manifest = decodeManifest( + readFileSync(join(root, "maps/maple-sourcemaps.json"), "utf8"), + ) + const first = yield* stack.deploy(SourceMaps("maps", props)) + expect(first.uploaded).toBe(2) + expect( + Arr.map(h.uploads, (u) => [ + u.path, + u.query, + u.contentType, + u.body === + readFileSync( + join( + root, + "maps", + `${Str.replace("static/", "")(u.query["minified_path"] ?? "")}.map`, + ), + "utf8", + ), + ]), + ).toEqual( + Arr.map(manifest.files, (file) => [ + "/v2/source_maps", + { + minified_path: `static/${file.file}`, + service: "web", + debug_id: file.debugId, + version: "abc123", + }, + "application/json", + true, + ]), + ) + expect([...first.debugIds].sort()).toEqual( + Arr.map(manifest.files, (file) => file.debugId).sort(), + ) + + // Unchanged maps: a noop, nothing uploaded. + h.uploads.length = 0 + expect((yield* stack.plan(SourceMaps("maps", props))).resources.maps?.action).toBe("noop") + const second = yield* stack.deploy(SourceMaps("maps", props)) + expect([second.digest, h.uploads.length]).toEqual([first.digest, 0]) + + // A rebuild that changed a map uploads again. + yield* buildOutput(root, "src/b-changed.ts") + const third = yield* stack.deploy(SourceMaps("maps", props)) + expect(third.digest).not.toBe(first.digest) + expect(h.uploads.length).toBe(2) + + // Deleting uploads and deletes nothing: older releases still need their maps. + h.uploads.length = 0 + yield* stack.destroy() + expect(h.uploads).toEqual([]) + }), + ) + }) + + it.live("matched by release, uploads without debug ids, in the query or the map", () => { + const h = makeHarness() + const stack = h.stack("by-release") + const root = mkdtempSync(join(tmpdir(), "maple-maps-")) + const props = { dir: join(root, "maps"), service: "maple-web", release: "sha-1" } + return h.run( + Effect.gen(function* () { + yield* buildOutput(root) + const result = yield* stack.deploy( + SourceMaps("maps", { ...props, matchBy: "release" as const }), + ) + expect([result.uploaded, result.debugIds]).toEqual([2, []]) + expect(Arr.map(h.uploads, (u) => u.query)).toEqual([ + { minified_path: "assets/a.js", service: "maple-web", version: "sha-1" }, + { minified_path: "assets/b.js", service: "maple-web", version: "sha-1" }, + ]) + Arr.forEach(h.uploads, (u) => { + const body = decodeMap(u.body) + expect(["debugId" in body, "debug_id" in body, body["mappings"]]).toEqual([ + false, + false, + ";AAAA;AACA", + ]) + }) + // The default keeps the debug ids, so switching mode uploads again. + h.uploads.length = 0 + yield* stack.deploy(SourceMaps("maps", props)) + expect(Arr.every(h.uploads, (u) => u.query["debug_id"] !== undefined)).toBe(true) + expect(Arr.every(h.uploads, (u) => "debugId" in decodeMap(u.body))).toBe(true) + }), + ) + }) + + it.live("reads maps beside their JS without a manifest, skipping ones it cannot match", () => { + const h = makeHarness() + const stack = h.stack("plain-dir") + const root = mkdtempSync(join(tmpdir(), "maple-maps-")) + writeFileSync(join(root, "main.js"), "m()\n") + writeFileSync(join(root, "main.js.map"), map("src/main.ts")) + mkdirSync(join(root, "big")) + writeFileSync(join(root, "big/huge.js"), "h()\n") + writeFileSync( + join(root, "big/huge.js.map"), + `${Str.slice(0, -1)(map("src/huge.ts"))},"pad":"${Str.repeat(10 * 1024 * 1024)("x")}"}`, + ) + return h.run( + Effect.gen(function* () { + // No release and no debug id: nothing can match the map, so nothing goes up. + const without = yield* stack.deploy(SourceMaps("maps", { dir: root, service: "api" })) + expect([without.uploaded, h.uploads.length]).toEqual([0, 0]) + const withRelease = yield* stack.deploy( + SourceMaps("maps", { dir: root, service: "api", release: "v2" }), + ) + expect(withRelease.uploaded).toBe(1) + expect(Arr.map(h.uploads, (u) => u.query)).toEqual([ + { minified_path: "main.js", service: "api", version: "v2" }, + ]) + expect(Option.isNone(Option.fromNullishOr(h.uploads[0]?.query["debug_id"]))).toBe(true) + }), + ) + }) + + it.live("uploads nothing and keeps its record when the directory is gone", () => { + const h = makeHarness() + const stack = h.stack("missing-dir") + const root = mkdtempSync(join(tmpdir(), "maple-maps-")) + return h.run( + Effect.gen(function* () { + const result = yield* stack.deploy( + SourceMaps("maps", { dir: join(root, "never-built"), service: "web", release: "1" }), + ) + expect([result.uploaded, h.uploads.length]).toEqual([0, 0]) + }), + ) + }) +}) diff --git a/packages/alchemy-maple/test/status-page.test.ts b/packages/alchemy-maple/test/status-page.test.ts index 3bc679efdd..9023f6675d 100644 --- a/packages/alchemy-maple/test/status-page.test.ts +++ b/packages/alchemy-maple/test/status-page.test.ts @@ -173,6 +173,7 @@ const makeFake = () => { patch: (path, body) => Effect.suspend(() => route("PATCH", path, body)), put: (path, body) => Effect.suspend(() => route("PUT", path, body)), delete: (path) => Effect.suspend(() => route("DELETE", path)), + upload: (path) => Effect.die(`unexpected upload ${path}`), } return { api, diff --git a/packages/alchemy-maple/test/uptime-monitor.test.ts b/packages/alchemy-maple/test/uptime-monitor.test.ts index 85e49e8d79..8184a3219d 100644 --- a/packages/alchemy-maple/test/uptime-monitor.test.ts +++ b/packages/alchemy-maple/test/uptime-monitor.test.ts @@ -63,6 +63,7 @@ const makeFake = () => { calls.push({ method: "DELETE", path }) store.delete(path) }), + upload: (path) => Effect.die(`unexpected upload ${path}`), } return { api, calls, store } } diff --git a/packages/alchemy-maple/test/vite.test.ts b/packages/alchemy-maple/test/vite.test.ts new file mode 100644 index 0000000000..e7746cdf1f --- /dev/null +++ b/packages/alchemy-maple/test/vite.test.ts @@ -0,0 +1,158 @@ +import { afterEach, beforeEach, describe, expect, it } from "vitest" +import { originalPositionFor, TraceMap } from "@jridgewell/trace-mapping" +import { Array as Arr, Effect, Option, Order, Result, Schema, String as Str } from "effect" +import { SourceMapsManifest } from "@maple/sourcemaps" +import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { build } from "vite" +import { mapleSourceMaps, processBuildOutputs } from "../src/Vite" +import * as NodeServices from "@effect/platform-node/NodeServices" + +const decodeManifest = Schema.decodeUnknownSync(Schema.fromJsonString(SourceMapsManifest)) + +const SOURCE = Arr.join( + [ + "export function thrower(x) {", + " if (x > 1) {", + ' throw new Error("boom-from-line-3")', + " }", + " return x", + "}", + "console.log(thrower(Math.random()))", + "", + ], + "\n", +) + +const walk = (dir: string): ReadonlyArray => + Arr.flatMap(readdirSync(dir, { withFileTypes: true }), (entry) => + entry.isDirectory() + ? Arr.map(walk(join(dir, entry.name)), (f) => `${entry.name}/${f}`) + : [entry.name], + ) + +let root = "" +beforeEach(() => { + root = mkdtempSync(join(tmpdir(), "maple-vite-")) + mkdirSync(join(root, "src")) + writeFileSync(join(root, "src/main.js"), SOURCE) +}) +afterEach(() => rmSync(root, { recursive: true, force: true })) + +describe("mapleSourceMaps", () => { + it("injects debug ids and moves every map out of the output, still mapping to the source", async () => { + await build({ + root, + configFile: false, + logLevel: "silent", + plugins: [mapleSourceMaps()], + build: { outDir: "dist", rolldownOptions: { input: join(root, "src/main.js") } }, + }) + + const output = walk(join(root, "dist")) + expect(Arr.filter(output, Str.endsWith(".map"))).toEqual([]) + const [jsFile] = Arr.filter(output, Str.endsWith(".js")) + expect(jsFile).toBeDefined() + const code = readFileSync(join(root, "dist", jsFile ?? ""), "utf8") + expect(code).toContain("_mapleDebugIds") + const debugId = /\/\/# debugId=([0-9a-f-]{36})/.exec(code)?.[1] + expect(debugId).toBeDefined() + expect(code).not.toContain("sourceMappingURL") + + const mapsDir = join(root, ".maple/sourcemaps/dist") + const manifest = JSON.parse(readFileSync(join(mapsDir, "maple-sourcemaps.json"), "utf8")) + expect(manifest).toEqual({ version: 1, files: [{ file: jsFile, debugId, map: `${jsFile}.map` }] }) + const map = JSON.parse(readFileSync(join(mapsDir, `${jsFile}.map`), "utf8")) + expect([map.debugId, map.debug_id, map.x_maple_shifted]).toEqual([debugId, debugId, debugId]) + expect(Str.startsWith(";")(map.mappings)).toBe(true) + + // The thrown message's generated position still maps to line 3 of the source. + const lines = Str.split("\n")(code) + const line = Arr.findFirstIndex(lines, Str.includes("boom-from-line-3")) + expect(line._tag).toBe("Some") + const generatedLine = line._tag === "Some" ? line.value : -1 + const column = Option.getOrElse(Str.indexOf("boom-from-line-3")(lines[generatedLine] ?? ""), () => -1) + const position = originalPositionFor(new TraceMap(map), { line: generatedLine + 1, column }) + expect([Str.endsWith("src/main.js")(position.source ?? ""), position.line]).toEqual([true, 3]) + }) + + it("relocates every output of a build that writes several into one dir", async () => { + await build({ + root, + configFile: false, + logLevel: "silent", + plugins: [mapleSourceMaps({ mapsDir: "maps" })], + build: { + outDir: "dist", + rolldownOptions: { + input: join(root, "src/main.js"), + output: [ + { dir: join(root, "dist"), entryFileNames: "esm-[name].js", format: "es" }, + { dir: join(root, "dist"), entryFileNames: "cjs-[name].js", format: "cjs" }, + ], + }, + }, + }) + const output = walk(join(root, "dist")) + expect(Arr.filter(output, Str.endsWith(".map"))).toEqual([]) + const manifest = decodeManifest(readFileSync(join(root, "maps/maple-sourcemaps.json"), "utf8")) + expect( + Arr.sort( + Arr.map(manifest.files, (file) => file.file), + Order.String, + ), + ).toEqual(["cjs-main.js", "esm-main.js"]) + expect(Arr.sort(Arr.filter(walk(join(root, "maps")), Str.endsWith(".map")), Order.String)).toEqual([ + "cjs-main.js.map", + "esm-main.js.map", + ]) + }) +}) + +describe("processBuildOutputs", () => { + const writeOutput = (dir: string) => { + mkdirSync(dir, { recursive: true }) + writeFileSync(join(dir, "a.js"), "a()\n") + writeFileSync( + join(dir, "a.js.map"), + JSON.stringify({ version: 3, sources: ["a.ts"], mappings: "AAAA" }), + ) + } + const run = (outDirs: ReadonlyArray, mapsDir: string) => + Effect.runPromise( + Effect.result(processBuildOutputs(outDirs, mapsDir)).pipe(Effect.provide(NodeServices.layer)), + ) + + it("refuses a maps dir that is, holds or sits inside the output, touching nothing", async () => { + const dist = join(root, "dist") + writeOutput(dist) + for (const mapsDir of [dist, join(dist, "maps"), root]) { + const result = await run([dist], mapsDir) + expect(Result.isFailure(result) ? result.failure._tag : "ok").toBe( + "@maple/sourcemaps/SourceMapsDirOverlapError", + ) + } + expect(Arr.sort(walk(dist), Order.String)).toEqual(["a.js", "a.js.map"]) + }) + + it("replaces only the previous build's maps, leaving other files in the maps dir", async () => { + const dist = join(root, "dist") + const maps = join(root, "maps") + mkdirSync(maps) + writeFileSync(join(maps, "keep.txt"), "mine") + writeOutput(dist) + await run([dist], maps) + expect(Arr.sort(walk(maps), Order.String)).toEqual(["a.js.map", "keep.txt", "maple-sourcemaps.json"]) + // The next build no longer emits a.js: its map goes, the unrelated file stays. + rmSync(dist, { recursive: true, force: true }) + mkdirSync(dist) + writeFileSync(join(dist, "b.js"), "b()\n") + writeFileSync( + join(dist, "b.js.map"), + JSON.stringify({ version: 3, sources: ["b.ts"], mappings: "AAAA" }), + ) + await run([dist], maps) + expect(Arr.sort(walk(maps), Order.String)).toEqual(["b.js.map", "keep.txt", "maple-sourcemaps.json"]) + }) +}) diff --git a/packages/alchemy-maple/tsconfig.json b/packages/alchemy-maple/tsconfig.json index 8bd7bfb1c3..df0d0b935a 100644 --- a/packages/alchemy-maple/tsconfig.json +++ b/packages/alchemy-maple/tsconfig.json @@ -7,6 +7,7 @@ "lib": ["ES2024"], "types": ["bun", "node"], "moduleResolution": "bundler", + "allowImportingTsExtensions": true, "verbatimModuleSyntax": true, "noEmit": true, "skipLibCheck": true, diff --git a/packages/alchemy-maple/tsdown.config.ts b/packages/alchemy-maple/tsdown.config.ts index 7e912d931f..b5fc840b4e 100644 --- a/packages/alchemy-maple/tsdown.config.ts +++ b/packages/alchemy-maple/tsdown.config.ts @@ -12,6 +12,7 @@ export default defineConfig({ telemetry: "./src/Telemetry.ts", local: "./src/Local.ts", "local-sidecar": "./src/LocalSidecar.ts", + vite: "./src/Vite.ts", }, format: "esm", dts: { tsconfig: "../../tsconfig.alchemy-maple.json" }, @@ -22,8 +23,8 @@ export default defineConfig({ loader: { ".sql": "text" }, define: { __CHDB_VERSION__: JSON.stringify(libchdbVersion) }, deps: { - neverBundle: ["effect", /^@effect\//, "alchemy", "@maple-dev/effect-sdk", /^bun:/], + neverBundle: ["effect", /^@effect\//, "alchemy", "@maple-dev/effect-sdk", "vite", /^bun:/], alwaysBundle: [/^@maple\//, /^@maple-dev\/effect-orm/], - onlyImport: ["effect", /^@effect\//, "alchemy", "@maple-dev/effect-sdk", /^node:/, /^bun:/], + onlyImport: ["effect", /^@effect\//, "alchemy", "@maple-dev/effect-sdk", "vite", /^node:/, /^bun:/], }, }) diff --git a/packages/backend/package.json b/packages/backend/package.json index d97294d7bd..22e4eae448 100644 --- a/packages/backend/package.json +++ b/packages/backend/package.json @@ -30,6 +30,7 @@ "@distilled.cloud/planetscale": "1.0.0-rc.20", "@distilled.cloud/supabase": "1.0.0-rc.20", "@distilled.cloud/vercel": "1.0.0-rc.20", + "@jridgewell/trace-mapping": "0.3.31", "@maple-dev/effect-clickhouse-http": "workspace:*", "@maple-dev/effect-orm": "0.10.0", "@maple/alerting-core": "workspace:*", diff --git a/packages/backend/src/platform/bindings.ts b/packages/backend/src/platform/bindings.ts index dfb8d33f9b..dd9388f045 100644 --- a/packages/backend/src/platform/bindings.ts +++ b/packages/backend/src/platform/bindings.ts @@ -9,7 +9,7 @@ */ import type { SecurityAuditWorkflowPayload } from "@maple/domain/security-audit" import type { ChatSessionClient } from "@maple/domain/chat-session-stub" -import { Context, type Effect, Layer, Option, Schema } from "effect" +import { Array as Arr, Clock, Context, Effect, Layer, Option, Order, Schema, String as Str } from "effect" export class QueueSendError extends Schema.TaggedError()( "@maple/backend/platform/QueueSendError", @@ -141,6 +141,82 @@ export class ReplayBlobEraser extends Context.Service Effect.Effect + /** Deleting a key that holds no object is not an error. */ + readonly delete: (keys: ReadonlyArray) => Effect.Effect + /** One page of objects under `prefix` in key order, after `startAfter` when given. */ + readonly list: (options: { + readonly prefix: string + readonly startAfter?: string | undefined + readonly limit: number + }) => Effect.Effect< + { readonly objects: ReadonlyArray; readonly truncated: boolean }, + ObjectStoreError + > +} + +/** A {@link WritableObjectStore} over `objects`, which the caller may inspect. */ +export const inMemoryObjectStore = (objects: Map): WritableObjectStore => { + const uploadedAt = new Map() + return { + getBytes: (key) => Effect.sync(() => Option.fromNullishOr(objects.get(key))), + put: (key, bytes) => + Effect.map(Clock.currentTimeMillis, (now) => { + objects.set(key, bytes) + uploadedAt.set(key, now) + }), + delete: (keys) => + Effect.sync(() => { + Arr.forEach(keys, (key) => objects.delete(key)) + }), + list: ({ prefix, startAfter, limit }) => + Effect.sync(() => { + const keys = Arr.filter( + Arr.sort(Array.from(objects.keys()), Order.String), + (key) => Str.startsWith(prefix)(key) && (startAfter === undefined || key > startAfter), + ) + return { + objects: Arr.map(Arr.take(keys, limit), (key) => ({ + key, + uploadedAt: uploadedAt.get(key) ?? 0, + })), + truncated: keys.length > limit, + } + }), + } +} + +/** Read side of the source map bucket: symbolication on hosts that never upload (the alerting tick). */ +export class SourceMapReadBucket extends Context.Service()( + "@maple/backend/platform/SourceMapReadBucket", +) {} + +/** Uploaded JavaScript source maps, read and written by the api. */ +export class SourceMapBucket extends Context.Service()( + "@maple/backend/platform/SourceMapBucket", +) {} + +/** Both sides of the source map bucket over one store, for the api and tests. */ +export const sourceMapBucketLayer = (store: WritableObjectStore) => + Layer.mergeAll(Layer.succeed(SourceMapBucket, store), Layer.succeed(SourceMapReadBucket, store)) + +/** The source map bucket's delete side, for erasing a deleted organization's uploads. */ +export class SourceMapEraser extends Context.Service()( + "@maple/backend/platform/SourceMapEraser", +) {} + /** What the Postgres layers dial: the Hyperdrive connection string and the identity attributes its spans carry. */ export interface DatabaseConnection { readonly connectionString: string diff --git a/packages/backend/src/services/audit-trail/providers/maple.ts b/packages/backend/src/services/audit-trail/providers/maple.ts index c12278f515..294ca498ce 100644 --- a/packages/backend/src/services/audit-trail/providers/maple.ts +++ b/packages/backend/src/services/audit-trail/providers/maple.ts @@ -25,6 +25,7 @@ const CATEGORY_BY_RESOURCE = { api_key: "credential", attribute_mapping: "configuration", ingest_rule: "configuration", + source_map: "configuration", data_source: "configuration", dashboard: "resource", chat_integration: "configuration", diff --git a/packages/backend/src/services/errors/ErrorGroupingService.test.ts b/packages/backend/src/services/errors/ErrorGroupingService.test.ts index 4656a1142f..76c20d0507 100644 --- a/packages/backend/src/services/errors/ErrorGroupingService.test.ts +++ b/packages/backend/src/services/errors/ErrorGroupingService.test.ts @@ -2,7 +2,13 @@ import { randomUUID } from "node:crypto" import { afterEach, assert, describe, it } from "@effect/vitest" import { Array as Arr, Clock, Effect, Layer, Schema } from "effect" import { ErrorIssueId, OrgId, UserId } from "@maple/primitives" -import { ErrorIssueFingerprints, ErrorIssues } from "@maple/db/tables" +import { ErrorGroupingKeys, ErrorIssueFingerprints, ErrorIssues } from "@maple/db/tables" +import type { SymbolicatedStack } from "@maple/domain/errors/js-stack" +import { explainGrouping, type GroupingSample, groupingKey } from "@maple/domain/tinybird/grouping" +import { + StackSymbolicator, + type StackSymbolicatorApi, +} from "@maple/backend/services/sourcemaps/StackSymbolicator" import * as PG from "@maple-dev/effect-orm/postgres" import { OrgGroupingRule } from "@maple/domain/tinybird/grouping-rules" import { GroupingRulesUpdateRequest } from "@maple/domain/http" @@ -55,7 +61,10 @@ const warehouseStub = (rows: WarehouseRows): WarehouseQueryServiceApi => ({ }, }) -const makeLayer = (rows: WarehouseRows = { samples: [], spans: [] }) => { +const makeLayer = ( + rows: WarehouseRows = { samples: [], spans: [] }, + symbolicator: Layer.Layer = Layer.empty, +) => { const database = createTestDb(createdDbs).layer const actors = ErrorActorsService.layer.pipe(Layer.provide(database)) const workflow = Layer.effect(ErrorIssueWorkflowService, ErrorIssueWorkflowService.make).pipe( @@ -63,7 +72,12 @@ const makeLayer = (rows: WarehouseRows = { samples: [], spans: [] }) => { ) const grouping = Layer.effect(ErrorGroupingService, ErrorGroupingService.make).pipe( Layer.provide( - Layer.mergeAll(database, workflow, Layer.succeed(WarehouseQueryService, warehouseStub(rows))), + Layer.mergeAll( + database, + workflow, + symbolicator, + Layer.succeed(WarehouseQueryService, warehouseStub(rows)), + ), ), ) return grouping.pipe(Layer.provideMerge(database)) @@ -184,6 +198,7 @@ describe("ErrorGroupingService.explainIssue", () => { const sample = (fingerprintHash: string, chunk: string) => ({ fingerprintHash, serviceName: "checkout-api", + serviceVersion: "", timestamp, traceId: `t-${fingerprintHash}`, spanId: `s-${fingerprintHash}`, @@ -236,4 +251,104 @@ describe("ErrorGroupingService.explainIssue", () => { ), ) }) + + it.effect("shows mapped frames only when they produced the stored key", () => { + const timestamp = formatWarehouseDateTime(Date.now() - 60_000) + const raw = "TypeError: boom\n at a (https://app.example/assets/x-1.js:1:1)" + const sampleRow = { + fingerprintHash: "2001", + serviceName: "web", + serviceVersion: "", + timestamp, + traceId: "t-2001", + spanId: "s-2001", + exceptionType: "TypeError", + statusMessage: "boom", + exceptionStacktrace: raw, + } + const spanRow = { + traceId: "t-2001", + spanId: "s-2001", + spanName: "render", + spanKind: "Internal", + spanFingerprint: "", + eventsName: '["exception"]', + eventsAttributes: "[{}]", + } + const mappedStack: SymbolicatedStack = { + status: "resolved", + missing: [], + frames: [ + { + raw: "at a (https://app.example/assets/x-1.js:1:1)", + function: "renderInvoice", + function_from_map: true, + file: "src/invoice.ts", + line: 12, + column: 3, + in_app: true, + resolved: true, + context: null, + }, + ], + } + const stacks: StackSymbolicatorApi = { + symbolicate: () => Effect.succeed(mappedStack), + symbolicateWithOutcome: () => Effect.succeed({ stack: mappedStack, lookupFailed: false }), + hasSourceMaps: () => Effect.succeed(true), + sourceMapsKnown: () => Effect.succeedSome(true), + } + const rawSample: GroupingSample = { + serviceName: "web", + exceptionType: "TypeError", + statusMessage: "boom", + exceptionStacktrace: raw, + span: { kind: "Internal", name: "render" }, + } + const framesWhenStored = (storedKey: string) => + Effect.gen(function* () { + const grouping = yield* ErrorGroupingService + const database = yield* Database + const issue = yield* seedIssue({ + fingerprintHash: "2001", + serviceName: "web", + exceptionType: "TypeError", + }) + yield* database.execute((db) => + db.run( + PG.insertInto(ErrorGroupingKeys).values({ + orgId: ORG, + fingerprintHash: "2001", + groupingKey: storedKey, + keyVersion: 1, + configDigest: "", + rule: "frames", + pinned: false, + createdAt: 0, + updatedAt: 0, + }), + ), + ) + const explained = yield* grouping.explainIssue(ORG, issue) + return explained.fingerprints[0]?.frames + }).pipe( + Effect.provide( + makeLayer( + { samples: [sampleRow], spans: [spanRow] }, + Layer.succeed(StackSymbolicator, stacks), + ), + ), + ) + return Effect.gen(function* () { + // Keyed on the raw stack before the map came: the raw frames are the evidence. + assert.deepStrictEqual( + yield* framesWhenStored(groupingKey(rawSample)), + explainGrouping(rawSample).frames, + ) + const mappedSample = { ...rawSample, symbolicatedStack: mappedStack } + assert.deepStrictEqual(yield* framesWhenStored(groupingKey(mappedSample)), [ + "at renderInvoice (src/invoice.ts)", + ]) + }) + }) }) diff --git a/packages/backend/src/services/errors/ErrorGroupingService.ts b/packages/backend/src/services/errors/ErrorGroupingService.ts index 9bb11d95eb..8ae8a3f8c3 100644 --- a/packages/backend/src/services/errors/ErrorGroupingService.ts +++ b/packages/backend/src/services/errors/ErrorGroupingService.ts @@ -25,13 +25,14 @@ import { type WarehouseReadError, } from "@maple/domain/http" import { computeFingerprintInputs } from "@maple/domain/tinybird/fingerprint" -import { explainGrouping, keyOfParts } from "@maple/domain/tinybird/grouping" +import { explainGrouping, type GroupingSample, keyOfParts } from "@maple/domain/tinybird/grouping" import { GroupingConfig, groupingRuleProblem } from "@maple/domain/tinybird/grouping-rules" import { Array as Arr, Clock, Context, DateTime, Effect, Layer, Order, Schema, String as Str } from "effect" import { Database } from "@maple/backend/platform/DatabaseLive" import { timestampMs } from "@maple/backend/platform/time" import { systemTenant } from "@maple/backend/services/auth/system-tenant" import { WarehouseQueryService } from "@maple/backend/services/warehouse/WarehouseQueryService" +import { StackSymbolicator } from "@maple/backend/services/sourcemaps/StackSymbolicator" import { ACTIONABLE_WORKFLOW_STATES } from "./ErrorIssueReadModelsService" import { ErrorIssueWorkflowService } from "./ErrorIssueWorkflowService" import { makeErrorDatabaseExecute } from "./error-persistence" @@ -39,6 +40,8 @@ import { computeSampleInputs, loadOrgGrouping, warehouseGroupingReads } from "./ /** Fingerprints one "why grouped" response explains; the rest are counted, not read. */ const MAX_EXPLAINED_FINGERPRINTS = 50 + +const withoutStack = ({ symbolicatedStack: _stack, ...sample }: GroupingSample): GroupingSample => sample /** Open issues a similar-issues read compares against, newest first. */ const SIMILAR_CANDIDATES = 500 const SIMILAR_LIMIT = 5 @@ -101,6 +104,8 @@ const make: Effect.Effect< const database = yield* Database const workflow = yield* ErrorIssueWorkflowService const warehouse = yield* WarehouseQueryService + // Explains a source-mapped key with its mapped frames where the source map bucket is bound. + const symbolicator = yield* Effect.serviceOption(StackSymbolicator) const dbExecute = makeErrorDatabaseExecute(database, "ErrorGroupingService") const document = (rules: GroupingConfig["rules"], updatedAt: number | null) => @@ -224,20 +229,34 @@ const make: Effect.Effect< orgId, { startMs: issue.firstSeenAt, endMs: issue.lastSeenAt + 60_000 }, "errorGroupingExplain", + symbolicator, ) const samples = yield* reads.samples(hashes) const spans = samples.length === 0 ? [] : yield* reads.spans(samples) - const inputs = new Map( - Arr.map(computeSampleInputs(samples, spans), (entry) => [entry.fingerprintHash, entry] as const), - ) + const entries = computeSampleInputs(samples, spans) + const mapped = + reads.sourceMapped === undefined || entries.length === 0 + ? entries + : yield* reads.sourceMapped(entries, grouping.rules) + const inputs = new Map(Arr.map(mapped, (entry) => [entry.fingerprintHash, entry] as const)) const sampleOf = new Map(Arr.map(samples, (sample) => [sample.fingerprintHash, sample] as const)) const fingerprints = Arr.map(explained, ({ fingerprintHash, source }) => { const entry = inputs.get(fingerprintHash) const sample = sampleOf.get(fingerprintHash) const key = storedOf.get(fingerprintHash) - const why = entry === undefined ? undefined : explainGrouping(entry.input, grouping.rules) // The stored rule is the one that grouped the hash; a pin-only row keyed nothing. const keyed = key !== undefined && !Str.startsWith("pinned:")(key.groupingKey) + const mappedWhy = entry === undefined ? undefined : explainGrouping(entry.input, grouping.rules) + // Mapped frames explain a stored key only when they produce it (a key stored before the + // maps came is still the raw one); otherwise the raw stack is the evidence. + const why = + entry === undefined || + mappedWhy === undefined || + !keyed || + entry.input.symbolicatedStack === undefined || + keyOfParts(entry.input.serviceName, mappedWhy) === key.groupingKey + ? mappedWhy + : explainGrouping(withoutStack(entry.input), grouping.rules) return new ErrorIssueFingerprintGrouping({ fingerprintHash, source, diff --git a/packages/backend/src/services/errors/ErrorIssueReadModelsService.test.ts b/packages/backend/src/services/errors/ErrorIssueReadModelsService.test.ts index 97eb7d33fc..486a943a2f 100644 --- a/packages/backend/src/services/errors/ErrorIssueReadModelsService.test.ts +++ b/packages/backend/src/services/errors/ErrorIssueReadModelsService.test.ts @@ -15,6 +15,10 @@ import { import { ErrorActorsService } from "./ErrorActorsService" import { ErrorIssueReadModelsService } from "./ErrorIssueReadModelsService" import { ErrorIssueWorkflowService } from "./ErrorIssueWorkflowService" +import { + type SymbolicateRequest, + StackSymbolicator, +} from "@maple/backend/services/sourcemaps/StackSymbolicator" import { compiledQueryOf } from "@maple/query-engine/execution" import { WarehouseSchemaDriftError } from "@maple/domain/http" @@ -36,6 +40,9 @@ const createdDbs: TestDb[] = [] afterEach(() => cleanupTestDbs(createdDbs)) +const BUNDLE_URL = "https://shop.example.com/assets/index-Bx81.js" +const DEBUG_ID = "6c5e2b1a-1f2e-4d3c-8b7a-0123456789ab" + /** What the warehouse holds for the issue detail reads, by query context. */ const WAREHOUSE_ROWS = new Map>>([ ["errorIssueEnvFingerprints", [{ fingerprintHash: "fp-checkout" }]], @@ -57,6 +64,36 @@ const WAREHOUSE_ROWS = new Map>>([ ], ], ["errorIssueEnvironments", [{ name: "production", count: 4 }]], + [ + "errorIssueLatestStacktrace", + [ + { + timestamp: "2026-11-05 10:01:02", + stacktrace: `TypeError: boom\n at a (${BUNDLE_URL}:1:1)`, + serviceName: "checkout-web", + serviceVersion: "2.4.0", + traceId: "0af7651916cd43dd8448eb211c80319c", + spanId: "b7ad6b7169203331", + }, + ], + ], + [ + "errorIssueLatestStackSpan", + [ + { + traceId: "0af7651916cd43dd8448eb211c80319c", + spanId: "b7ad6b7169203331", + spanName: "click", + spanKind: "Internal", + spanFingerprint: "", + eventsName: JSON.stringify(["log", "exception"]), + eventsAttributes: JSON.stringify([ + { "maple.exception.debug_ids": "{}" }, + { "maple.exception.debug_ids": JSON.stringify({ [BUNDLE_URL]: DEBUG_ID }) }, + ]), + }, + ], + ], ]) /** A cluster that has not applied migration 0057 rejects any read naming `UserId`. */ @@ -70,7 +107,10 @@ const missingUserId = (sql: string) => const makeWarehouseStub = ( contexts: Array, sqls: Array, - stubOptions: { withoutUserId?: boolean } = {}, + stubOptions: { + withoutUserId?: boolean + rows?: ReadonlyMap>> + } = {}, ): WarehouseQueryServiceApi => ({ query: () => Effect.die(new Error("unexpected pipe query")), rawSqlQuery: () => Effect.die(new Error("unexpected raw SQL query")), @@ -90,7 +130,11 @@ const makeWarehouseStub = ( ), Effect.andThen( compiledQueryOf(compiled) - .decodeRows(WAREHOUSE_ROWS.get(options?.context ?? "") ?? []) + .decodeRows( + stubOptions.rows?.get(options?.context ?? "") ?? + WAREHOUSE_ROWS.get(options?.context ?? "") ?? + [], + ) .pipe(Effect.orDie), ), ) @@ -108,7 +152,11 @@ const makeWarehouseStub = ( const makeLayer = ( contexts: Array, sqls: Array = [], - stubOptions: { withoutUserId?: boolean } = {}, + stubOptions: { + withoutUserId?: boolean + symbolicator?: Layer.Layer + rows?: ReadonlyMap>> + } = {}, ) => { const database = createTestDb(createdDbs).layer const actors = ErrorActorsService.layer.pipe(Layer.provide(database)) @@ -119,6 +167,7 @@ const makeLayer = ( ) const warehouse = Layer.succeed(WarehouseQueryService, makeWarehouseStub(contexts, sqls, stubOptions)) const readModels = readRequirements.pipe( + Layer.provide(stubOptions.symbolicator ?? Layer.empty), Layer.provide(database), Layer.provide(warehouse), Layer.provide(workflow), @@ -455,4 +504,121 @@ describe("ErrorIssueReadModelsService", () => { assert.lengthOf(contexts, 2) }).pipe(Effect.provide(makeLayer(contexts, sqls))) }) + + it.effect("symbolicates the latest stack with the debug ids on its exception event", () => { + const contexts: Array = [] + const requests: Array = [] + const symbolicator = Layer.succeed(StackSymbolicator, { + symbolicate: (request) => + Effect.sync(() => { + requests.push(request) + return { status: "missing_map" as const, frames: [], missing: [BUNDLE_URL] } + }), + symbolicateWithOutcome: () => Effect.die("symbolicateWithOutcome"), + hasSourceMaps: () => Effect.succeed(true), + sourceMapsKnown: () => Effect.succeedSome(true), + }) + return Effect.gen(function* () { + const readModels = yield* ErrorIssueReadModelsService + const now = yield* Clock.currentTimeMillis + const issueId = asIssueId(randomUUID()) + yield* seedIssue(ORG, issueId, now, { fingerprintHash: "fp-checkout" }) + + const detail = yield* readModels.getIssue(ORG, issueId, {}) + assert.deepStrictEqual(detail.latestStack, { + status: "missing_map", + frames: [], + missing: [BUNDLE_URL], + }) + assert.strictEqual(detail.latestStacktrace, `TypeError: boom\n at a (${BUNDLE_URL}:1:1)`) + assert.lengthOf(requests, 1) + const request = requests[0] + assert.strictEqual(request?.serviceName, "checkout-web") + assert.strictEqual(request?.serviceVersion, "2.4.0") + assert.deepStrictEqual(Array.from(request?.debugIds ?? []), [[BUNDLE_URL, DEBUG_ID]]) + assert.include(contexts, "errorIssueLatestStackSpan") + }).pipe(Effect.provide(makeLayer(contexts, [], { symbolicator }))) + }) + + it.effect("reads no span for a latest occurrence recorded without a trace or span", () => { + const contexts: Array = [] + const requests: Array = [] + const symbolicator = Layer.succeed(StackSymbolicator, { + symbolicate: (request) => + Effect.sync(() => { + requests.push(request) + return { status: "missing_map" as const, frames: [], missing: [BUNDLE_URL] } + }), + symbolicateWithOutcome: () => Effect.die("symbolicateWithOutcome"), + hasSourceMaps: () => Effect.succeed(true), + sourceMapsKnown: () => Effect.succeedSome(true), + }) + const rows = new Map([ + [ + "errorIssueLatestStacktrace", + [ + { + timestamp: "2026-11-05 10:01:02", + stacktrace: `TypeError: boom\n at a (${BUNDLE_URL}:1:1)`, + serviceName: "checkout-web", + serviceVersion: "2.4.0", + traceId: "", + spanId: "", + }, + ], + ], + ]) + return Effect.gen(function* () { + const readModels = yield* ErrorIssueReadModelsService + const now = yield* Clock.currentTimeMillis + const issueId = asIssueId(randomUUID()) + yield* seedIssue(ORG, issueId, now, { fingerprintHash: "fp-checkout" }) + + const detail = yield* readModels.getIssue(ORG, issueId, {}) + assert.strictEqual(detail.latestStack?.status, "missing_map") + assert.notInclude(contexts, "errorIssueLatestStackSpan") + assert.deepStrictEqual(Array.from(requests[0]?.debugIds ?? []), []) + }).pipe(Effect.provide(makeLayer(contexts, [], { symbolicator, rows }))) + }) + + it.effect("skips the span read for an org with no source maps, still returning the stack", () => { + const contexts: Array = [] + const requests: Array = [] + const symbolicator = Layer.succeed(StackSymbolicator, { + symbolicate: (request) => + Effect.sync(() => { + requests.push(request) + return { status: "missing_map" as const, frames: [], missing: [BUNDLE_URL] } + }), + symbolicateWithOutcome: () => Effect.die("symbolicateWithOutcome"), + hasSourceMaps: () => Effect.succeed(false), + sourceMapsKnown: () => Effect.succeedSome(false), + }) + return Effect.gen(function* () { + const readModels = yield* ErrorIssueReadModelsService + const now = yield* Clock.currentTimeMillis + const issueId = asIssueId(randomUUID()) + yield* seedIssue(ORG, issueId, now, { fingerprintHash: "fp-checkout" }) + + const detail = yield* readModels.getIssue(ORG, issueId, {}) + assert.strictEqual(detail.latestStack?.status, "missing_map") + assert.notInclude(contexts, "errorIssueLatestStackSpan") + assert.deepStrictEqual(Array.from(requests[0]?.debugIds ?? []), []) + }).pipe(Effect.provide(makeLayer(contexts, [], { symbolicator }))) + }) + + it.effect("leaves the latest stack null where no symbolicator is bound", () => { + const contexts: Array = [] + return Effect.gen(function* () { + const readModels = yield* ErrorIssueReadModelsService + const now = yield* Clock.currentTimeMillis + const issueId = asIssueId(randomUUID()) + yield* seedIssue(ORG, issueId, now, { fingerprintHash: "fp-checkout" }) + + const detail = yield* readModels.getIssue(ORG, issueId, {}) + assert.isNotNull(detail.latestStacktrace) + assert.isNull(detail.latestStack) + assert.notInclude(contexts, "errorIssueLatestStackSpan") + }).pipe(Effect.provide(makeLayer(contexts))) + }) }) diff --git a/packages/backend/src/services/errors/ErrorIssueReadModelsService.ts b/packages/backend/src/services/errors/ErrorIssueReadModelsService.ts index 7aefb95a7d..e7fe5becde 100644 --- a/packages/backend/src/services/errors/ErrorIssueReadModelsService.ts +++ b/packages/backend/src/services/errors/ErrorIssueReadModelsService.ts @@ -19,6 +19,7 @@ import { type IssueKind, type IssueSeverity, type OrgId, + type TenantContext, UserId as UserIdSchema, type WorkflowState, type WarehouseReadError, @@ -35,6 +36,9 @@ import { makeErrorDatabaseExecute } from "./error-persistence" import { issueFingerprintHashes } from "./issue-fingerprints" import { severityRank } from "./issue-severity" import { systemTenant } from "@maple/backend/services/auth/system-tenant" +import { StackSymbolicator } from "@maple/backend/services/sourcemaps/StackSymbolicator" +import { DEBUG_IDS_ATTRIBUTE, decodeDebugIds, parseJsStack } from "@maple/domain/errors/js-stack" +import { exceptionEventAttribute } from "./exception-event" const decodeErrorIssueIdSync = Schema.decodeUnknownSync(ErrorIssueDocument.fields.id) const encodeIssueListCursor = Schema.encodeSync(IssueListCursor) @@ -46,6 +50,8 @@ const decodeUserIdSync = Schema.decodeUnknownSync(UserIdSchema) const SYSTEM_USER_ID = decodeUserIdSync("system-errors") const DEFAULT_DETAIL_WINDOW_MS = 24 * 60 * 60 * 1000 +/** error_events keeps whole seconds; the span behind an occurrence starts within its second. */ +const LATEST_SPAN_WINDOW_MS = 60_000 /** Fallback fingerprint-scan window for the issue list's env filter when the * caller provides no time range (30d ≈ the issue-list retention horizon). */ const ENV_FINGERPRINT_DEFAULT_WINDOW_MS = 30 * 24 * 60 * 60 * 1000 @@ -235,8 +241,107 @@ const make: Effect.Effect< const database = yield* Database const warehouse = yield* WarehouseQueryService const workflow = yield* ErrorIssueWorkflowService + // Hosts without the source map bucket (the MCP runtime) leave `latestStack` null. + const symbolicator = yield* Effect.serviceOption(StackSymbolicator) const dbExecute = makeErrorDatabaseExecute(database, "ErrorIssueReadModelsService") + /** The debug ids the SDK put on the occurrence's exception event; empty when its span cannot be read. */ + const occurrenceDebugIds = ( + tenant: TenantContext, + orgId: OrgId, + occurrence: { + readonly serviceName: string + readonly traceId: string + readonly spanId: string + readonly timestamp: DateTime.Utc + }, + ) => { + // An occurrence recorded without a trace or span has no exception event to read. + if (occurrence.traceId === "" || occurrence.spanId === "") { + return Effect.succeed(new Map()) + } + const atMs = DateTime.toEpochMillis(occurrence.timestamp) + return warehouse + .compiledQuery( + tenant, + CH.compile( + CH.errorGroupingSpansQuery({ + serviceNames: [occurrence.serviceName], + traceIds: [occurrence.traceId], + spanIds: [occurrence.spanId], + }), + { + orgId, + startTime: DateTime.makeUnsafe(atMs - LATEST_SPAN_WINDOW_MS), + endTime: DateTime.makeUnsafe(atMs + LATEST_SPAN_WINDOW_MS), + }, + ), + { profile: "list", context: "errorIssueLatestStackSpan" }, + ) + .pipe( + Effect.map((spans) => + decodeDebugIds( + Option.getOrUndefined( + Option.flatMapNullishOr(Arr.head(spans), (span) => + exceptionEventAttribute(span, DEBUG_IDS_ATTRIBUTE), + ), + ), + ), + ), + Effect.catch((error) => + Effect.logWarning("Latest occurrence span could not be read for debug ids").pipe( + Effect.annotateLogs({ orgId, message: error.message }), + Effect.as(new Map()), + ), + ), + ) + } + + /** Whether the org has any source map; false on a host with no symbolicator. */ + const orgHasSourceMaps = (orgId: OrgId) => + Option.match(symbolicator, { + onNone: () => Effect.succeed(false), + onSome: (stacks) => stacks.hasSourceMaps(orgId), + }) + + /** + * The occurrence's stack mapped through the org's source maps; null on a host with no + * symbolicator. An org without maps skips the span read: there is nothing to look its ids up in. + */ + const latestStackOf = ( + tenant: TenantContext, + orgId: OrgId, + occurrence: Parameters[2] & { + readonly stacktrace: string + readonly serviceVersion: string + }, + hasMaps: boolean, + ) => + Option.match(symbolicator, { + onNone: () => Effect.succeed(null), + onSome: (stacks) => { + const hasFileFrames = + hasMaps && + Arr.some(parseJsStack(occurrence.stacktrace).frames, (frame) => frame.url !== null) + return ( + hasFileFrames + ? occurrenceDebugIds(tenant, orgId, occurrence) + : Effect.succeed(new Map()) + ).pipe( + Effect.flatMap((debugIds) => + stacks.symbolicate({ + orgId, + stacktrace: occurrence.stacktrace, + serviceName: occurrence.serviceName === "" ? null : occurrence.serviceName, + serviceVersion: + occurrence.serviceVersion === "" ? null : occurrence.serviceVersion, + debugIds, + }), + ), + ) + }, + }) + const rowToIncident = (row: ErrorIncidentRow) => new ErrorIncidentDocument({ id: row.id, @@ -541,12 +646,30 @@ const make: Effect.Effect< ), ) - const [timeseriesRows, sampleRows, environmentRows, stacktraceRows, incidentRows] = yield* Effect.all( - [timeseriesEffect, samplesEffect, environmentsEffect, stacktraceEffect, incidentsEffect], - { concurrency: 5 }, + const [timeseriesRows, sampleRows, environmentRows, stacktraceRows, incidentRows, hasMaps] = + yield* Effect.all( + [ + timeseriesEffect, + samplesEffect, + environmentsEffect, + stacktraceEffect, + incidentsEffect, + isErrorKind ? orgHasSourceMaps(orgId) : Effect.succeed(false), + ], + { concurrency: 6 }, + ) + const latestOccurrence = stacktraceRows[0] + const latestStacktrace = latestOccurrence?.stacktrace ?? null + // The span read needs the latest occurrence, so it runs beside the issue hydration instead. + const [latestStack, issue] = yield* Effect.all( + [ + latestOccurrence === undefined + ? Effect.succeed(null) + : latestStackOf(tenant, orgId, latestOccurrence, hasMaps), + workflow.hydrateIssue(orgId, issueRow), + ], + { concurrency: 2 }, ) - const latestStacktrace = stacktraceRows[0]?.stacktrace ?? null - const issue = yield* workflow.hydrateIssue(orgId, issueRow) const timeseries = Arr.map( timeseriesRows, (row) => @@ -583,6 +706,7 @@ const make: Effect.Effect< incidents: Arr.map(incidentRows, rowToIncident), environments, latestStacktrace, + latestStack, }) }) diff --git a/packages/backend/src/services/errors/ErrorsService.test.ts b/packages/backend/src/services/errors/ErrorsService.test.ts index b2a5acd612..dc8ce8091f 100644 --- a/packages/backend/src/services/errors/ErrorsService.test.ts +++ b/packages/backend/src/services/errors/ErrorsService.test.ts @@ -5438,6 +5438,7 @@ describe("ErrorsService.runTick grouping keys", () => { const sample = (fingerprintHash: string, chunk: string) => ({ fingerprintHash, serviceName: "checkout-api", + serviceVersion: "", timestamp: formatWarehouseDateTime(TICK_MS - 90_000), traceId: `trace-${fingerprintHash}`, spanId: `span-${fingerprintHash}`, diff --git a/packages/backend/src/services/errors/ErrorsService.ts b/packages/backend/src/services/errors/ErrorsService.ts index 0fd2e3a744..57a2a68ccb 100644 --- a/packages/backend/src/services/errors/ErrorsService.ts +++ b/packages/backend/src/services/errors/ErrorsService.ts @@ -80,6 +80,7 @@ import { type NotificationRequest, } from "@maple/backend/services/alerts/NotificationDispatcher" import { WarehouseQueryService } from "@maple/backend/services/warehouse/WarehouseQueryService" +import { StackSymbolicator } from "@maple/backend/services/sourcemaps/StackSymbolicator" import { OrgClickHouseSettingsService } from "@maple/backend/services/org/OrgClickHouseSettingsService" import { EdgeCacheService } from "@maple/cache" import { @@ -297,6 +298,8 @@ const make: Effect.Effect< const earlyPromotionsPerDay = yield* EarlyPromotionsPerDay // Starts the investigation agent when an incident opens (org opt-in). const starter = yield* InvestigationStarter + // Grouping keys read source-mapped frames where the host binds the source map bucket. + const symbolicator = yield* Effect.serviceOption(StackSymbolicator) const newErrorIssueId = () => decodeErrorIssueIdSync(randomUUID()) const newErrorIncidentId = () => decodeErrorIncidentIdSync(randomUUID()) @@ -1419,6 +1422,7 @@ const make: Effect.Effect< orgId, { startMs: windowStartMs, endMs: windowEndMs }, "errorGrouping", + symbolicator, ), { orgId, diff --git a/packages/backend/src/services/errors/exception-event.ts b/packages/backend/src/services/errors/exception-event.ts new file mode 100644 index 0000000000..436fb053c9 --- /dev/null +++ b/packages/backend/src/services/errors/exception-event.ts @@ -0,0 +1,22 @@ +import { Array as Arr, Option, Schema } from "effect" + +const decodeJson = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown)) +const decodeNames = Schema.decodeUnknownOption(Schema.Array(Schema.String)) +const decodeAttributes = Schema.decodeUnknownOption(Schema.Array(Schema.Record(Schema.String, Schema.String))) + +/** A span's events as the warehouse returns them: `toJSONString(EventsName)` and `toJSONString(EventsAttributes)`. */ +export interface SpanEventsJson { + readonly eventsName: string + readonly eventsAttributes: string +} + +/** An attribute of the span's first `exception` event, as the error-events view reads that event. */ +export const exceptionEventAttribute = (span: SpanEventsJson, key: string): string | undefined => { + const names = Option.getOrElse(Option.flatMap(decodeJson(span.eventsName), decodeNames), () => []) + const attributes = Option.getOrElse( + Option.flatMap(decodeJson(span.eventsAttributes), decodeAttributes), + () => [], + ) + const index = Arr.findFirstIndex(names, (name) => name === "exception") + return Option.getOrUndefined(Option.flatMap(index, (i) => Option.fromNullishOr(attributes[i]?.[key]))) +} diff --git a/packages/backend/src/services/errors/grouping-keys.test.ts b/packages/backend/src/services/errors/grouping-keys.test.ts new file mode 100644 index 0000000000..928e0bbb6a --- /dev/null +++ b/packages/backend/src/services/errors/grouping-keys.test.ts @@ -0,0 +1,933 @@ +import { TraceMap } from "@jridgewell/trace-mapping" +import { compileGroupingRules, GroupingConfig, OrgGroupingRule } from "@maple/domain/tinybird/grouping-rules" +import { explainGrouping, groupingKey } from "@maple/domain/tinybird/grouping" +import { OrgId } from "@maple/domain/http" +import { Array as Arr, DateTime, Effect, Option, Order, Record as Rec, Schema, String as Str } from "effect" +import { afterEach, describe, expect, it } from "vitest" +import * as PG from "@maple-dev/effect-orm/postgres" +import { ErrorFingerprintCandidates, ErrorGroupingKeys } from "@maple/db/tables" +import { Database } from "@maple/backend/platform/DatabaseLive" +import { cleanupTestDbs, createTestDb, type TestDb } from "@maple/backend/testing/test-pglite" +import type { StackSymbolicatorApi } from "@maple/backend/services/sourcemaps/StackSymbolicator" +import { symbolicateStack } from "@maple/backend/services/sourcemaps/symbolicate" +import { + computeSampleInputs, + DEFAULT_ORG_GROUPING, + type GroupingSampleRow, + type GroupingSpanRow, + MAP_PENDING_GRACE_MS, + resolveGroupingSiblings, + withSourceMappedStacks, +} from "./grouping-keys" + +const createdDbs: TestDb[] = [] +afterEach(() => cleanupTestDbs(createdDbs)) + +const ORG = Schema.decodeSync(OrgId)("org_grouping_keys_test") +const BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" + +/** Base64 VLQ, as the source map v3 spec encodes each segment field. */ +const vlq = (value: number): string => { + const digits = (rest: number): ReadonlyArray => + rest < 32 ? [rest] : [(rest & 31) | 32, ...digits(rest >>> 5)] + return Arr.join( + Arr.map(digits(value < 0 ? (-value << 1) | 1 : value << 1), (digit) => BASE64[digit] ?? ""), + "", + ) +} + +type Segment = readonly [genColumn: number, source: number, line: number, column: number, name: number] + +/** One generated line of absolute (0-based) segments, every one named. */ +const encodeLine = (segments: ReadonlyArray): string => + Arr.join( + Arr.map(segments, (segment, i) => { + const previous = i === 0 ? ([0, 0, 0, 0, 0] as const) : (segments[i - 1] ?? segment) + return Arr.join( + Arr.map([0, 1, 2, 3, 4] as const, (field) => vlq(segment[field] - previous[field])), + "", + ) + }), + ",", + ) + +/** One release's bundle: an app function at `appColumn`, a dependency's at `libColumn`. */ +const release = (opts: { + readonly bundle: string + readonly appFunction: string + readonly appSource?: string + readonly appLine: number + readonly appColumn: number + readonly libColumn: number + readonly libFunction?: string + readonly noSourceText?: boolean +}) => ({ + url: `https://app.example.com/assets/${opts.bundle}.js`, + map: new TraceMap({ + version: 3, + file: `${opts.bundle}.js`, + sources: [ + `webpack://web/./${opts.appSource ?? "src/invoice.ts"}`, + "webpack://web/./node_modules/ky/index.js", + ], + // The throw site's own text, wherever the release put it: what an unnamed frame keys on. + sourcesContent: [ + opts.noSourceText === true + ? null + : Arr.join( + Arr.makeBy(opts.appLine + 1, (i) => + i === opts.appLine ? " return invoice.total" : "", + ), + "\n", + ), + null, + ], + names: [opts.appFunction, opts.libFunction ?? "request"], + mappings: encodeLine([ + [opts.appColumn, 0, opts.appLine, 2, 0], + [opts.libColumn, 1, 40, 4, 1], + ]), + }), + app: (minified: string) => + `${minified} (https://app.example.com/assets/${opts.bundle}.js:1:${opts.appColumn + 1})`, + lib: (minified: string) => + `${minified} (https://app.example.com/assets/${opts.bundle}.js:1:${opts.libColumn + 1})`, +}) + +const V1 = release({ + bundle: "index-Bx81", + appFunction: "renderInvoice", + appLine: 6, + appColumn: 0, + libColumn: 40, +}) +const V2 = release({ + bundle: "index-Qz07", + appFunction: "renderInvoice", + appLine: 19, + appColumn: 120, + libColumn: 900, + libFunction: "retry", +}) +const CART = release({ + bundle: "index-Qz07b", + appFunction: "renderCart", + appSource: "src/cart.ts", + appLine: 3, + appColumn: 7, + libColumn: 60, +}) +// No embedded source: a throw site with no caller maps, but has no identity to key on. +const BARE = release({ + bundle: "index-bare", + appFunction: "renderInvoice", + appLine: 6, + appColumn: 0, + libColumn: 40, + noSourceText: true, +}) +const MAPS = new Map(Arr.map([V1, V2, CART, BARE], (r) => [r.url, r.map] as const)) + +/** The symbolicator, over in-memory maps; counts its lookups and can fail them. */ +const symbolicator = (options: { readonly lookupFails?: boolean } = {}) => { + const calls: Array = [] + const symbolicateWithOutcome: StackSymbolicatorApi["symbolicateWithOutcome"] = (request) => + Effect.sync(() => { + calls.push(request.stacktrace) + return { + stack: symbolicateStack(request.stacktrace, (frame) => + frame.url === null || options.lookupFails === true ? undefined : MAPS.get(frame.url), + ), + lookupFailed: options.lookupFails === true, + } + }) + const api: StackSymbolicatorApi = { + symbolicate: (request) => Effect.map(symbolicateWithOutcome(request), (outcome) => outcome.stack), + symbolicateWithOutcome, + hasSourceMaps: () => Effect.succeed(true), + sourceMapsKnown: () => Effect.succeedSome(true), + } + return { api, calls } +} + +const sampleRow = ( + hash: string, + type: string, + message: string, + frames: ReadonlyArray, +): GroupingSampleRow => ({ + fingerprintHash: hash, + serviceName: "web", + serviceVersion: "", + timestamp: DateTime.makeUnsafe(1_700_000_000_000), + traceId: `trace-${hash}`, + spanId: `span-${hash}`, + exceptionType: type, + statusMessage: message, + exceptionStacktrace: Arr.join([`${type}: ${message}`, ...Arr.map(frames, (f) => ` at ${f}`)], "\n"), +}) + +const spanRow = (hash: string, fingerprint = ""): GroupingSpanRow => ({ + traceId: `trace-${hash}`, + spanId: `span-${hash}`, + spanName: "render", + spanKind: "Internal", + spanFingerprint: fingerprint, + eventsName: '["exception"]', + eventsAttributes: "[{}]", +}) + +const MESSAGE = "Cannot read properties of undefined (reading 'total')" +const DEBUG_ID_FOR_TEST = "6c5e2b1a-1f2e-4d3c-8b7a-0123456789ab" +const v1Sample = sampleRow("q1", "TypeError", MESSAGE, [V1.app("a")]) + +/** Each sample keyed as the tick keys it, with or without a symbolicator. */ +const keysOf = ( + samples: ReadonlyArray, + options: { + readonly stacks?: StackSymbolicatorApi + readonly fingerprints?: Record + readonly rules?: ReturnType + } = {}, +) => + Arr.map( + Effect.runSync( + withSourceMappedStacks( + Option.fromNullishOr(options.stacks), + ORG, + computeSampleInputs( + samples, + Arr.map(samples, (s) => + spanRow(s.fingerprintHash, options.fingerprints?.[s.fingerprintHash]), + ), + ), + options.rules, + ), + ), + (entry) => ({ + key: groupingKey(entry.input, options.rules), + why: explainGrouping(entry.input, options.rules), + }), + ) + +describe("grouping keys over source maps", () => { + const v1 = sampleRow("h1", "TypeError", MESSAGE, [V1.app("a")]) + const v2 = sampleRow("h2", "TypeError", MESSAGE, [V2.app("xe")]) + + it("joins one bug across two releases that renamed its function and bundle", () => { + const [rawA, rawB] = keysOf([v1, v2]) + expect(rawA?.key).not.toBe(rawB?.key) + const { api } = symbolicator() + const [a, b] = keysOf([v1, v2], { stacks: api }) + expect(a?.key).toBe(b?.key) + expect(a?.why.rule).toBe("source-mapped") + // The throw site has no caller to name it, so it keys on its source line's text. + expect(a?.why.frames).toEqual(["at src/invoice.ts | return invoice.total"]) + }) + + it("keeps a different original function apart", () => { + const cart = sampleRow("h3", "TypeError", MESSAGE, [CART.app("xe")]) + const { api } = symbolicator() + const [a, c] = keysOf([v1, cart], { stacks: api }) + expect(a?.key).not.toBe(c?.key) + }) + + it("reads past dependency frames to the app's own", () => { + const viaKy = sampleRow("h4", "TypeError", MESSAGE, [V1.lib("t"), V1.app("a")]) + const viaRetry = sampleRow("h5", "TypeError", MESSAGE, [V2.lib("q"), V2.app("xe")]) + const { api } = symbolicator() + const [a, b] = keysOf([viaKy, viaRetry], { stacks: api }) + expect(a?.key).toBe(b?.key) + expect(a?.why.skippedFrames).toHaveLength(1) + expect(a?.why.skippedFrames[0]).toMatch(/\(node_modules\/ky\/index\.js\)$/) + }) + + it("keys a partly mapped stack on the frames that mapped", () => { + const withVendor = (bundle: string, r: typeof V1, minified: string, hash: string) => + sampleRow(hash, "TypeError", MESSAGE, [ + r.app(minified), + `Zt (https://app.example.com/assets/${bundle}.js:3:77)`, + ]) + const { api } = symbolicator() + const [a, b] = keysOf( + [withVendor("vendor-77", V1, "a", "h6"), withVendor("vendor-9f", V2, "xe", "h7")], + { + stacks: api, + }, + ) + expect(a?.key).toBe(b?.key) + expect(a?.why.rule).toBe("source-mapped") + }) + + it("leaves custom fingerprints and org merge rules in charge, without a lookup", () => { + const { api, calls } = symbolicator() + const [custom] = keysOf([v1], { stacks: api, fingerprints: { h1: "invoice-total" } }) + expect(custom?.why.rule).toBe("custom") + const rules = compileGroupingRules( + new GroupingConfig({ + rules: [new OrgGroupingRule({ id: "reads", kind: "merge", message: "*reading*" })], + }), + ) + const [merged] = keysOf([v1], { stacks: api, rules }) + expect(merged?.why.rule).toBe("org-rule") + expect(calls).toEqual([]) + }) + + it("keys exactly as before with no symbolicator, no JS frames, or no map", () => { + const python = sampleRow("h8", "ValueError", "", []) + const pythonStack = { + ...python, + exceptionStacktrace: 'Traceback:\n File "/app/worker.py", line 3, in run\nValueError', + } + const unmapped = sampleRow("h9", "TypeError", MESSAGE, [ + "a (https://app.example.com/assets/index-unknown.js:1:1)", + ]) + const { api, calls } = symbolicator() + const plain = keysOf([pythonStack, unmapped]) + const looked = keysOf([pythonStack, unmapped], { stacks: api }) + expect(Arr.map(looked, (k) => k.key)).toEqual(Arr.map(plain, (k) => k.key)) + expect(calls).toHaveLength(1) + }) +}) + +describe("keys that wait for a source map", () => { + const NOW = 1_700_000_000_000 + const unmapped = sampleRow("p1", "TypeError", MESSAGE, [ + "a (https://app.example.com/assets/index-unknown.js:1:1)", + ]) + const mapped = sampleRow("p2", "TypeError", MESSAGE, [V1.app("a")]) + // A vendor chunk: its map loads and every frame maps into `node_modules`. + const vendor = sampleRow("p3", "TypeError", MESSAGE, [V1.lib("t")]) + + /** The hashes keyed by one tick at `NOW`, each hash first seen `firstSeenAgoMs` earlier. */ + const keyedBy = ( + samples: ReadonlyArray, + stacks: StackSymbolicatorApi, + firstSeenAgoMs: Readonly> = {}, + ) => + Effect.runPromise( + Effect.gen(function* () { + const database = yield* Database + const seen = Rec.toEntries(firstSeenAgoMs) + if (seen.length > 0) { + yield* database.execute((db) => + db.run( + PG.insertInto(ErrorFingerprintCandidates).values( + Arr.map(seen, ([fingerprintHash, ago]) => ({ + orgId: ORG, + fingerprintHash, + serviceName: "web", + exceptionType: "TypeError", + exceptionMessage: MESSAGE, + topFrame: "", + firstSeenAt: NOW - ago, + lastSeenAt: NOW, + updatedAt: NOW, + })), + ), + ), + ) + } + yield* resolveGroupingSiblings( + (run) => database.execute(run), + { + samples: () => Effect.succeed(samples), + spans: (rows) => Effect.succeed(Arr.map(rows, (row) => spanRow(row.fingerprintHash))), + sourceMapped: (entries, rules) => + withSourceMappedStacks(Option.some(stacks), ORG, entries, rules), + }, + { + orgId: ORG, + hashes: Arr.map(samples, (sample) => sample.fingerprintHash), + nowMs: NOW, + grouping: DEFAULT_ORG_GROUPING, + lineage: new Map(), + }, + ) + const rows = yield* database.execute((db) => + db.run( + PG.from(ErrorGroupingKeys) + .select("fingerprintHash") + .where(($) => [$.orgId.eq(ORG)]), + ), + ) + return Arr.sort( + Arr.map(rows, (row) => row.fingerprintHash), + Order.String, + ) + }).pipe(Effect.provide(createTestDb(createdDbs).layer)), + ) + + it("holds a first sighting whose frames found no map, and keys a mapped one", async () => { + const { api } = symbolicator() + expect(await keyedBy([unmapped, mapped], api)).toEqual(["p2"]) + }) + + it("holds a throw site an app rule claims on a dependency path, though its caller mapped", () => { + const ours = compileGroupingRules( + new GroupingConfig({ + rules: [ + new OrgGroupingRule({ id: "ours", kind: "app-frames", frame: "*node_modules/@acme/*" }), + ], + }), + ) + const claimed = sampleRow("p7", "TypeError", MESSAGE, [ + "t (https://app.example.com/node_modules/@acme/ui/index.js:1:1)", + V1.app("a"), + ]) + const entries = computeSampleInputs([claimed], [spanRow("p7")]) + const [entry] = Effect.runSync( + withSourceMappedStacks(Option.some(symbolicator().api), ORG, entries, ours), + ) + expect(entry?.mapPending).toBe(true) + const [plain] = Effect.runSync(withSourceMappedStacks(Option.some(symbolicator().api), ORG, entries)) + expect(plain?.mapPending).toBe(false) + }) + + it("waits for a first map only on a debug id recorded for one of the stack's own frames", () => { + const { api } = symbolicator() + const mapless: StackSymbolicatorApi = { ...api, hasSourceMaps: () => Effect.succeed(false) } + const withIds = (ids: Record) => + Effect.runSync( + withSourceMappedStacks( + Option.some(mapless), + ORG, + computeSampleInputs( + [v1Sample], + [ + { + ...spanRow("q1"), + eventsAttributes: JSON.stringify([ + { "maple.exception.debug_ids": JSON.stringify(ids) }, + ]), + }, + ], + ), + ), + )[0]?.mapPending + expect(withIds({ "https://app.example.com/assets/other.js": DEBUG_ID_FOR_TEST })).not.toBe(true) + expect(withIds({ [V1.url]: DEBUG_ID_FOR_TEST })).toBe(true) + }) + + it("keys a vendor chunk that mapped into dependencies at once", async () => { + const { api } = symbolicator() + expect(await keyedBy([vendor], api)).toEqual(["p3"]) + }) + + it("holds a hash whose lookup failed while it is young", async () => { + const { api } = symbolicator({ lookupFails: true }) + expect( + await keyedBy([unmapped, mapped], api, { p1: MAP_PENDING_GRACE_MS - 60_000, p2: 5 * 60_000 }), + ).toEqual([]) + }) + + it("keys on raw frames once the hash was first seen over the window ago, however fresh its sample", async () => { + const { api } = symbolicator({ lookupFails: true }) + expect( + await keyedBy([unmapped, mapped], api, { + p1: MAP_PENDING_GRACE_MS, + p2: 3 * MAP_PENDING_GRACE_MS, + }), + ).toEqual(["p1", "p2"]) + }) + + /** A stored mapped key for `p2`, under rules since changed, after one tick re-keys it from `sample`. */ + const storedAfterRekey = ( + api: StackSymbolicatorApi, + sample: GroupingSampleRow, + storedRule: "source-mapped" | "frames" = "source-mapped", + ) => + Effect.runPromise( + Effect.gen(function* () { + const database = yield* Database + // First seen long ago, keyed on mapped frames under rules since changed: the tick re-keys it. + yield* database.execute((db) => + db.run( + PG.insertInto(ErrorFingerprintCandidates).values({ + orgId: ORG, + fingerprintHash: "p2", + serviceName: "web", + exceptionType: "TypeError", + exceptionMessage: MESSAGE, + topFrame: "", + firstSeenAt: NOW - 3 * MAP_PENDING_GRACE_MS, + lastSeenAt: NOW, + updatedAt: NOW, + }), + ), + ) + yield* database.execute((db) => + db.run( + PG.insertInto(ErrorGroupingKeys).values({ + orgId: ORG, + fingerprintHash: "p2", + groupingKey: "mapped-key", + keyVersion: 1, + configDigest: "rules-before", + rule: storedRule, + pinned: false, + createdAt: 0, + updatedAt: 0, + }), + ), + ) + yield* resolveGroupingSiblings( + (run) => database.execute(run), + { + samples: () => Effect.succeed([{ ...sample, fingerprintHash: "p2" }]), + spans: (rows) => Effect.succeed(Arr.map(rows, (row) => spanRow(row.fingerprintHash))), + sourceMapped: (entries, rules) => + withSourceMappedStacks(Option.some(api), ORG, entries, rules), + }, + { + orgId: ORG, + hashes: ["p2"], + nowMs: NOW, + grouping: DEFAULT_ORG_GROUPING, + lineage: new Map(), + }, + ) + return yield* database.execute((db) => + db.run( + PG.from(ErrorGroupingKeys) + .select("groupingKey", "configDigest") + .where(($) => [$.orgId.eq(ORG)]), + ), + ) + }).pipe(Effect.provide(createTestDb(createdDbs).layer)), + ) + + it("keeps a stored key whose re-key lookup failed, however old the hash", async () => { + const { api } = symbolicator({ lookupFails: true }) + expect(await storedAfterRekey(api, mapped)).toEqual([ + { groupingKey: "mapped-key", configDigest: "rules-before" }, + ]) + }) + + it("re-keys a stored raw key after a rules change, whatever its lookup gave", async () => { + const bare = sampleRow("p2", "TypeError", MESSAGE, [BARE.app("a")]) + const pending = sampleRow("p2", "TypeError", MESSAGE, [ + "a (https://app.example.com/assets/index-unknown.js:1:1)", + ]) + const cases = [ + [symbolicator({ lookupFails: true }).api, mapped], + [symbolicator().api, pending], + [symbolicator().api, bare], + ] as const + const after = await Effect.runPromise( + Effect.forEach(cases, ([api, sample]) => + Effect.promise(() => storedAfterRekey(api, sample, "frames")), + ), + ) + Arr.forEach(after, (rows) => expect(Arr.map(rows, (row) => row.configDigest)).toEqual([""])) + }) + + it("keeps a stored key when the stack maps but gives nothing to key on", async () => { + const { api } = symbolicator() + const bare = sampleRow("p2", "TypeError", MESSAGE, [BARE.app("a")]) + expect(await storedAfterRekey(api, bare)).toEqual([ + { groupingKey: "mapped-key", configDigest: "rules-before" }, + ]) + }) + + it("keeps a stored key whose map is pending instead of re-keying it on minified frames", async () => { + const { api } = symbolicator() + expect(await storedAfterRekey(api, unmapped)).toEqual([ + { groupingKey: "mapped-key", configDigest: "rules-before" }, + ]) + // A sample that maps does re-key. + expect(await storedAfterRekey(api, mapped)).not.toEqual([ + { groupingKey: "mapped-key", configDigest: "rules-before" }, + ]) + }) + + it("holds a first sighting whose throw site did not map, even when its app caller did", async () => { + const throwSite = (hash: string, bundle: string) => + sampleRow(hash, "TypeError", MESSAGE, [ + `t (https://app.example.com/assets/${bundle}.js:1:1)`, + V1.app("a"), + ]) + const { api } = symbolicator() + expect( + await keyedBy([throwSite("p5", "index-one"), throwSite("p6", "index-two"), mapped], api), + ).toEqual(["p2"]) + }) + + it("holds a first sighting whose app frames did not map, even when a dependency frame did", async () => { + const mixed = sampleRow("p4", "TypeError", MESSAGE, [ + "a (https://app.example.com/assets/index-unknown.js:1:1)", + V1.lib("t"), + ]) + const { api } = symbolicator() + expect(await keyedBy([mixed, vendor], api)).toEqual(["p3"]) + }) + + it("reads first sightings only past the per-tick cap", async () => { + const statementsFor = (count: number) => + Effect.runPromise( + Effect.gen(function* () { + const database = yield* Database + const runs = { count: 0 } + yield* resolveGroupingSiblings( + (run) => + Effect.suspend(() => { + runs.count += 1 + return database.execute(run) + }), + { + samples: () => Effect.succeed([]), + spans: () => Effect.succeed([]), + sourceMapped: (entries) => Effect.succeed(entries), + mapsInPlay: Effect.succeedSome(false), + }, + { + orgId: ORG, + hashes: Arr.makeBy(count, (i) => `n${i}`), + nowMs: NOW, + grouping: DEFAULT_ORG_GROUPING, + lineage: new Map(), + }, + ) + return runs.count + }).pipe(Effect.provide(createTestDb(createdDbs).layer)), + ) + // The stored-key read; past the cap, one first-sighting read more to order the hashes. + expect(await statementsFor(200)).toBe(1) + expect(await statementsFor(201)).toBe(2) + }) +}) + +describe("an org's first source map upload", () => { + const NOW = 1_700_000_000_000 + const DEBUG_ID = "6c5e2b1a-1f2e-4d3c-8b7a-0123456789ab" + const v1 = sampleRow("f1", "TypeError", MESSAGE, [V1.app("a")]) + const v2 = sampleRow("f2", "TypeError", MESSAGE, [V2.app("xe")]) + + /** One tick over `samples`, with or without maps; spans carry the debug ids given per hash. */ + const tick = ( + database: (typeof Database)["Service"], + samples: ReadonlyArray, + hasMaps: Option.Option, + debugIds: Readonly>> = {}, + nowMs: number = NOW, + ) => { + const { api } = symbolicator() + const stacks: StackSymbolicatorApi = { + ...api, + hasSourceMaps: () => Effect.succeed(Option.getOrElse(hasMaps, () => true)), + sourceMapsKnown: () => Effect.succeed(hasMaps), + } + return resolveGroupingSiblings( + (run) => database.execute(run), + { + samples: (hashes) => + Effect.succeed(Arr.filter(samples, (s) => Arr.contains(hashes, s.fingerprintHash))), + spans: (rows) => + Effect.succeed( + Arr.map(rows, (row) => { + const ids = debugIds[row.fingerprintHash] + return ids === undefined + ? spanRow(row.fingerprintHash) + : { + ...spanRow(row.fingerprintHash), + eventsAttributes: JSON.stringify([ + { "maple.exception.debug_ids": JSON.stringify(ids) }, + ]), + } + }), + ), + sourceMapped: (entries, rules) => + withSourceMappedStacks(Option.some(stacks), ORG, entries, rules), + mapsInPlay: stacks.sourceMapsKnown(ORG), + }, + { + orgId: ORG, + hashes: Arr.map(samples, (sample) => sample.fingerprintHash), + nowMs, + grouping: DEFAULT_ORG_GROUPING, + lineage: new Map(), + }, + ) + } + + const storedKeys = (database: (typeof Database)["Service"]) => + database.execute((db) => + db.run( + PG.from(ErrorGroupingKeys) + .select("fingerprintHash", "groupingKey", "configDigest") + .where(($) => [$.orgId.eq(ORG)]) + .orderBy(($) => [[$.fingerprintHash, "asc"]]), + ), + ) + + it("re-keys a raw key once maps exist, so the next release joins it", async () => { + const result = await Effect.runPromise( + Effect.gen(function* () { + const database = yield* Database + yield* tick(database, [v1], Option.some(false)) + const before = yield* storedKeys(database) + // The org uploads its first maps; v1 recurs and the next release throws. + const siblings = yield* tick(database, [v1, v2], Option.some(true)) + return { before, after: yield* storedKeys(database), siblings } + }).pipe(Effect.provide(createTestDb(createdDbs).layer)), + ) + expect(result.before).toEqual([ + { fingerprintHash: "f1", groupingKey: keysOf([v1])[0]?.key, configDigest: "" }, + ]) + const mappedKey = keysOf([v1], { stacks: symbolicator().api })[0]?.key + expect(result.after).toEqual([ + { fingerprintHash: "f1", groupingKey: mappedKey, configDigest: "+source-maps" }, + { fingerprintHash: "f2", groupingKey: mappedKey, configDigest: "+source-maps" }, + ]) + expect(result.siblings.get("f2")).toEqual(["f1"]) + }) + + it("keeps an org without maps on today's digest", async () => { + const keys = await Effect.runPromise( + Effect.gen(function* () { + const database = yield* Database + yield* tick(database, [v1], Option.some(false)) + yield* tick(database, [v1], Option.some(false)) + return yield* storedKeys(database) + }).pipe(Effect.provide(createTestDb(createdDbs).layer)), + ) + expect(Arr.map(keys, (row) => row.configDigest)).toEqual([""]) + }) + + it("re-keys nothing when the has-maps lookup fails", async () => { + const result = await Effect.runPromise( + Effect.gen(function* () { + const database = yield* Database + // f1 keyed before the org had maps, f2 after: neither moves on a failed lookup. + yield* tick(database, [v1], Option.some(false)) + yield* tick(database, [v2], Option.some(true)) + const before = yield* storedKeys(database) + yield* tick(database, [v1, v2], Option.none()) + return { before, after: yield* storedKeys(database) } + }).pipe(Effect.provide(createTestDb(createdDbs).layer)), + ) + expect(Arr.map(result.before, (row) => row.configDigest)).toEqual(["", "+source-maps"]) + expect(result.after).toEqual(result.before) + }) + + const seedSeen = ( + database: (typeof Database)["Service"], + seen: ReadonlyArray, + ) => + database.execute((db) => + db.run( + PG.insertInto(ErrorFingerprintCandidates).values( + Arr.map(seen, ([fingerprintHash, firstSeenAt]) => ({ + orgId: ORG, + fingerprintHash, + serviceName: "web", + exceptionType: "TypeError", + exceptionMessage: MESSAGE, + topFrame: "", + firstSeenAt, + lastSeenAt: NOW, + updatedAt: NOW, + })), + ), + ), + ) + + it("lets a ready hash past 200 held for a first map in a mapless org within two ticks", async () => { + const held = Arr.makeBy(200, (i) => + sampleRow(`w${Str.padStart(3, "0")(String(i))}`, "TypeError", MESSAGE, [V1.app("a")]), + ) + const ready = sampleRow("zz-ready", "TypeError", MESSAGE, [V1.app("a")]) + const ids = Rec.fromEntries( + Arr.map(held, (row) => [row.fingerprintHash, { [V1.url]: DEBUG_ID }] as const), + ) + const keyed = await Effect.runPromise( + Effect.gen(function* () { + const database = yield* Database + yield* seedSeen( + database, + Arr.map([...held, ready], (row) => [row.fingerprintHash, NOW - 5 * 60_000] as const), + ) + yield* tick(database, [...held, ready], Option.some(false), ids) + yield* tick(database, [...held, ready], Option.some(false), ids, NOW + 60_000) + return Arr.map(yield* storedKeys(database), (row) => row.fingerprintHash) + }).pipe(Effect.provide(createTestDb(createdDbs).layer)), + ) + expect(keyed).toEqual(["zz-ready"]) + }) + + it("keeps re-keying stale keys during a storm of new hashes", async () => { + const storm = Arr.makeBy(250, (i) => `s${Str.padStart(3, "0")(String(i))}`) + const stale = Arr.makeBy(10, (i) => sampleRow(`stale-${i}`, "TypeError", MESSAGE, [V1.app("a")])) + const digests = await Effect.runPromise( + Effect.gen(function* () { + const database = yield* Database + yield* database.execute((db) => + db.run( + PG.insertInto(ErrorGroupingKeys).values( + Arr.map(stale, (row) => ({ + orgId: ORG, + fingerprintHash: row.fingerprintHash, + groupingKey: "old-key", + keyVersion: 1, + configDigest: "rules-before", + rule: "frames" as const, + pinned: false, + createdAt: 0, + updatedAt: 0, + })), + ), + ), + ) + yield* resolveGroupingSiblings( + (run) => database.execute(run), + { + samples: (hashes) => + Effect.succeed(Arr.filter(stale, (s) => Arr.contains(hashes, s.fingerprintHash))), + spans: (rows) => Effect.succeed(Arr.map(rows, (row) => spanRow(row.fingerprintHash))), + mapsInPlay: Effect.succeedSome(false), + }, + { + orgId: ORG, + hashes: [...storm, ...Arr.map(stale, (row) => row.fingerprintHash)], + nowMs: NOW, + grouping: DEFAULT_ORG_GROUPING, + lineage: new Map(), + }, + ) + return Arr.map(yield* storedKeys(database), (row) => row.configDigest) + }).pipe(Effect.provide(createTestDb(createdDbs).layer)), + ) + expect(digests).toEqual(Arr.makeBy(10, () => "")) + }) + + it("keeps expired hashes that never find a span from taking every slot", async () => { + const noSpan = Arr.makeBy(200, (i) => `y${Str.padStart(3, "0")(String(i))}`) + const fresh = sampleRow("new-one", "TypeError", MESSAGE, [V1.app("a")]) + const keyed = await Effect.runPromise( + Effect.gen(function* () { + const database = yield* Database + yield* seedSeen( + database, + Arr.map(noSpan, (hash) => [hash, NOW - 2 * MAP_PENDING_GRACE_MS] as const), + ) + // Only `new-one` has a sample and span; the 200 old hashes come back with nothing. + yield* resolveGroupingSiblings( + (run) => database.execute(run), + { + samples: (hashes) => + Effect.succeed( + Arr.filter([fresh], (s) => Arr.contains(hashes, s.fingerprintHash)), + ), + spans: (rows) => Effect.succeed(Arr.map(rows, (row) => spanRow(row.fingerprintHash))), + mapsInPlay: Effect.succeedSome(false), + }, + { + orgId: ORG, + hashes: [...noSpan, "new-one"], + nowMs: NOW, + grouping: DEFAULT_ORG_GROUPING, + lineage: new Map(), + }, + ) + return Arr.map(yield* storedKeys(database), (row) => row.fingerprintHash) + }).pipe(Effect.provide(createTestDb(createdDbs).layer)), + ) + expect(keyed).toEqual(["new-one"]) + }) + + it("keys a hash held past its grace window even behind 200 first sightings", async () => { + const fresh = Arr.makeBy(200, (i) => + sampleRow(`x${Str.padStart(3, "0")(String(i))}`, "TypeError", MESSAGE, [V1.app("a")]), + ) + const expired = sampleRow("old", "TypeError", MESSAGE, [ + "a (https://app.example.com/assets/index-unknown.js:1:1)", + ]) + const keyed = await Effect.runPromise( + Effect.gen(function* () { + const database = yield* Database + yield* seedSeen(database, [["old", NOW - MAP_PENDING_GRACE_MS]]) + yield* tick(database, [...fresh, expired], Option.some(true)) + return Arr.map(yield* storedKeys(database), (row) => row.fingerprintHash) + }).pipe(Effect.provide(createTestDb(createdDbs).layer)), + ) + expect(keyed).toContain("old") + }) + + it("keeps a raw key stored past the grace window when its map comes later (known limit)", async () => { + // The release's map arrives only after the hash keyed on raw frames: the stored key stays. + const late = sampleRow("late", "TypeError", MESSAGE, [ + "a (https://app.example.com/assets/index-late.js:1:1)", + ]) + const phase = { mapped: false } + const lateStacks: StackSymbolicatorApi = { + ...symbolicator().api, + symbolicateWithOutcome: (request) => + Effect.sync(() => ({ + stack: symbolicateStack(request.stacktrace, () => (phase.mapped ? V1.map : undefined)), + lookupFailed: false, + })), + } + const keys = await Effect.runPromise( + Effect.gen(function* () { + const database = yield* Database + yield* seedSeen(database, [["late", NOW - MAP_PENDING_GRACE_MS]]) + const once = () => + resolveGroupingSiblings( + (run) => database.execute(run), + { + samples: () => Effect.succeed([late]), + spans: (rows) => + Effect.succeed(Arr.map(rows, (row) => spanRow(row.fingerprintHash))), + sourceMapped: (entries, rules) => + withSourceMappedStacks(Option.some(lateStacks), ORG, entries, rules), + mapsInPlay: Effect.succeedSome(true), + }, + { + orgId: ORG, + hashes: ["late"], + nowMs: NOW, + grouping: DEFAULT_ORG_GROUPING, + lineage: new Map(), + }, + ) + yield* once() + const before = yield* storedKeys(database) + phase.mapped = true + yield* once() + return { before, after: yield* storedKeys(database) } + }).pipe(Effect.provide(createTestDb(createdDbs).layer)), + ) + expect(keys.before).toHaveLength(1) + expect(keys.after).toEqual(keys.before) + }) + + it("holds a young sample that registered debug ids before the org has any map", async () => { + const ids = { f1: { [V1.url]: DEBUG_ID } } + const keyed = (firstSeenAgo: number) => + Effect.runPromise( + Effect.gen(function* () { + const database = yield* Database + yield* database.execute((db) => + db.run( + PG.insertInto(ErrorFingerprintCandidates).values({ + orgId: ORG, + fingerprintHash: "f1", + serviceName: "web", + exceptionType: "TypeError", + exceptionMessage: MESSAGE, + topFrame: "", + firstSeenAt: NOW - firstSeenAgo, + lastSeenAt: NOW, + updatedAt: NOW, + }), + ), + ) + yield* tick(database, [v1, v2], Option.some(false), ids) + return Arr.map(yield* storedKeys(database), (row) => row.fingerprintHash) + }).pipe(Effect.provide(createTestDb(createdDbs).layer)), + ) + // f2 carries no debug ids: nothing says a map is coming, so it keys at once. + expect(await keyed(5 * 60_000)).toEqual(["f2"]) + expect(await keyed(MAP_PENDING_GRACE_MS)).toEqual(["f1", "f2"]) + }) +}) diff --git a/packages/backend/src/services/errors/grouping-keys.ts b/packages/backend/src/services/errors/grouping-keys.ts index d73b757398..0531965d44 100644 --- a/packages/backend/src/services/errors/grouping-keys.ts +++ b/packages/backend/src/services/errors/grouping-keys.ts @@ -1,9 +1,19 @@ import * as PG from "@maple-dev/effect-orm/postgres" import type { MapleDb, MapleDbError } from "@maple/db/client" -import { ErrorGroupingConfigs, ErrorGroupingKeys } from "@maple/db/tables" +import { + ErrorFingerprintCandidates, + ErrorGroupingConfigs, + ErrorGroupingKeys, + ErrorIssueFingerprints, + ErrorIssues, +} from "@maple/db/tables" import type { OrgId, TenantContext, WarehouseReadError } from "@maple/domain/http" import { CH } from "@maple/query-engine" import type { WarehouseQueryService } from "@maple/backend/services/warehouse/WarehouseQueryService" +import type { StackSymbolicatorApi } from "@maple/backend/services/sourcemaps/StackSymbolicator" +import type { SourceMapFileRow } from "@maple/db/tables" +import { hasDebugIdFor, isLookupUrl } from "@maple/backend/services/sourcemaps/source-map-files" +import { DEBUG_IDS_ATTRIBUTE, decodeDebugIds, isInAppPath, parseJsStack } from "@maple/domain/errors/js-stack" import { resolveCustomFingerprint } from "@maple/domain/tinybird/fingerprint" import { compileGroupingRules, @@ -19,19 +29,25 @@ import { type GroupingRule, type GroupingSample, } from "@maple/domain/tinybird/grouping" -import { Array as Arr, DateTime, Effect, Option, Order, Schema } from "effect" +import { Array as Arr, DateTime, Effect, Option, Order, String as Str } from "effect" import { describeCause } from "./error-persistence" +import { exceptionEventAttribute } from "./exception-event" /** Hashes keyed per tick at most; the rest wait for their next occurrence. */ const GROUPING_KEYS_PER_TICK = 200 /** Siblings handed to one hash at most: enough to fold a group, bounded for a storm. */ const MAX_SIBLINGS = 50 const CHUNK = 500 +/** How long a sample whose app frames found no map waits for one: the deploy-then-upload gap. */ +export const MAP_PENDING_GRACE_MS = 60 * 60_000 +/** Source map lookups run at once per tick; each is cached per isolate by the symbolicator. */ +const SYMBOLICATE_CONCURRENCY = 4 export interface GroupingSampleRow { readonly fingerprintHash: string readonly serviceName: string + readonly serviceVersion: string readonly timestamp: DateTime.Utc readonly traceId: string readonly spanId: string @@ -56,21 +72,19 @@ export interface ComputedKey { readonly rule: GroupingRule } -const decodeJson = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown)) -const decodeNames = Schema.decodeUnknownOption(Schema.Array(Schema.String)) -const decodeAttributes = Schema.decodeUnknownOption(Schema.Array(Schema.Record(Schema.String, Schema.String))) - -/** The first exception event's `maple.fingerprint`, as the error-events view reads it. */ -const eventFingerprint = (span: GroupingSpanRow): string | undefined => { - const names = Option.getOrElse(Option.flatMap(decodeJson(span.eventsName), decodeNames), () => []) - const attributes = Option.getOrElse( - Option.flatMap(decodeJson(span.eventsAttributes), decodeAttributes), - () => [], - ) - const index = Arr.findFirstIndex(names, (name) => name === "exception") - return Option.getOrUndefined( - Option.flatMap(index, (i) => Option.fromNullishOr(attributes[i]?.["maple.fingerprint"])), - ) +export interface SampleInput { + readonly fingerprintHash: string + readonly input: GroupingSample + /** What a source map lookup needs beyond the sample. */ + readonly serviceVersion: string + readonly debugIds: ReadonlyMap + /** + * The org has maps, yet the stack has frames one could map and none of its frames mapped: + * its map may still be on its way, so a young hash is not keyed yet. + */ + readonly mapPending?: boolean + /** A map lookup or read failed: a key from this sample may be missing frames that do map. */ + readonly lookupFailed?: boolean } /** @@ -81,13 +95,13 @@ const eventFingerprint = (span: GroupingSpanRow): string | undefined => { export const computeSampleInputs = ( samples: ReadonlyArray, spans: ReadonlyArray, -): Array<{ readonly fingerprintHash: string; readonly input: GroupingSample }> => { +): Array => { const spanOf = new Map(Arr.map(spans, (span) => [`${span.traceId}:${span.spanId}`, span] as const)) return Arr.flatMap(samples, (sample) => { const span = spanOf.get(`${sample.traceId}:${sample.spanId}`) if (span === undefined) return [] const customFingerprint = resolveCustomFingerprint( - eventFingerprint(span), + exceptionEventAttribute(span, "maple.fingerprint"), span.spanFingerprint === "" ? undefined : span.spanFingerprint, ) const base: GroupingSample = { @@ -98,16 +112,155 @@ export const computeSampleInputs = ( span: { kind: span.spanKind, name: span.spanName }, } const input: GroupingSample = customFingerprint === undefined ? base : { ...base, customFingerprint } - return [{ fingerprintHash: sample.fingerprintHash, input }] + return [ + { + fingerprintHash: sample.fingerprintHash, + input, + serviceVersion: sample.serviceVersion, + debugIds: decodeDebugIds(exceptionEventAttribute(span, DEBUG_IDS_ATTRIBUTE)), + }, + ] }) } +/** + * In an org with no maps yet, a sample whose build registered debug ids is waiting for its first + * upload: its frames could map, so a young hash is not keyed on raw frames. + */ +const withFirstMapPending = (entry: SampleInput, rules: CompiledGroupingRules | undefined): SampleInput => { + if (entry.debugIds.size === 0) return entry + const rule = groupingParts(entry.input, rules).rule + if (rule !== "frames" && rule !== "type-function") return entry + const frames = parseJsStack(entry.input.exceptionStacktrace).frames + // Only a debug id recorded for one of this stack's own app frames says a map is coming. + return Arr.some( + frames, + (frame) => + frame.url !== null && + hasDebugIdFor(frame.url, entry.debugIds) && + isAppFrame(frame, entry.input, rules), + ) + ? { ...entry, mapPending: true } + : entry +} + +/** An app frame by the org's frame rules (on the generated frame) first, else by its path. */ +const isAppFrame = ( + frame: { readonly raw: string; readonly url: string | null }, + sample: GroupingSample, + rules: CompiledGroupingRules | undefined, +): boolean => { + const kind = rules?.frameKind(frame.raw, sample) + return kind === undefined ? frame.url !== null && isInAppPath(frame.url) : kind === "app" +} + +/** + * Samples whose key reads frames, with their stack mapped through the org's source maps, + * so a deploy's renamed bundle keeps its key. Only a JS stack with frame URLs is looked up; + * every other sample, and every host without the symbolicator, keys as before. + */ +export const withSourceMappedStacks = ( + symbolicator: Option.Option, + orgId: OrgId, + entries: ReadonlyArray, + rules?: CompiledGroupingRules, +): Effect.Effect> => + Option.match(symbolicator, { + onNone: () => Effect.succeed(entries), + onSome: (stacks) => + Effect.flatMap( + Effect.all([ + stacks.hasSourceMaps(orgId), + Effect.sync(() => new Map()), + ]), + // One lookup per frame URL for the whole tick, shared by its samples. + ([hasMaps, lookupMemo]) => + !hasMaps + ? Effect.succeed(Arr.map(entries, (entry) => withFirstMapPending(entry, rules))) + : Effect.forEach( + entries, + (entry) => { + const rule = groupingParts(entry.input, rules).rule + const readsFrames = rule === "frames" || rule === "type-function" + const frames = parseJsStack(entry.input.exceptionStacktrace).frames + if ( + !readsFrames || + !Arr.some( + frames, + (frame) => + frame.url !== null && isLookupUrl(frame.url, entry.debugIds), + ) + ) { + return Effect.succeed(entry) + } + return stacks + .symbolicateWithOutcome({ + orgId, + stacktrace: entry.input.exceptionStacktrace, + serviceName: + entry.input.serviceName === "" + ? null + : entry.input.serviceName, + serviceVersion: + entry.serviceVersion === "" ? null : entry.serviceVersion, + debugIds: entry.debugIds, + lookupMemo, + }) + .pipe( + Effect.map(({ stack, lookupFailed }) => { + // Decided on the raw frames: a vendor chunk whose frames map into + // `node_modules` is mapped, not waiting. + const candidate = (frame: (typeof frames)[number]) => + frame.url !== null && + isLookupUrl(frame.url, entry.debugIds) && + isAppFrame(frame, entry.input, rules) + const unmapped = (i: number) => + stack.frames[i]?.resolved !== true + // The throw site waits for its map even when a caller below it mapped: + // keyed on that caller alone, two throw sites would share a key. + const throwSiteWaits = Option.match( + Arr.findFirstIndex(frames, candidate), + { + onNone: () => false, + onSome: unmapped, + }, + ) + const mapPending = + throwSiteWaits || + // A dependency frame that mapped says nothing about the app's own map. + (!Arr.some( + stack.frames, + (frame) => frame.resolved && frame.in_app, + ) && + Arr.some( + frames, + (frame, i) => candidate(frame) && unmapped(i), + )) + return stack.status === "resolved" || + stack.status === "partial" + ? { + ...entry, + input: { + ...entry.input, + symbolicatedStack: stack, + }, + mapPending, + lookupFailed, + } + : { ...entry, mapPending, lookupFailed } + }), + ) + }, + { concurrency: SYMBOLICATE_CONCURRENCY }, + ), + ), + }) + const computeGroupingKeys = ( - samples: ReadonlyArray, - spans: ReadonlyArray, + entries: ReadonlyArray, rules?: CompiledGroupingRules, ): Array => - Arr.map(computeSampleInputs(samples, spans), ({ fingerprintHash, input }) => { + Arr.map(entries, ({ fingerprintHash, input }) => { const parts = groupingParts(input, rules) return { fingerprintHash, groupingKey: keyOfParts(input.serviceName, parts), rule: parts.rule } }) @@ -162,7 +315,13 @@ export const warehouseGroupingReads = ( orgId: OrgId, window: { readonly startMs: number; readonly endMs: number }, context: string, + symbolicator: Option.Option = Option.none(), ): GroupingKeyReads => ({ + sourceMapped: (entries, rules) => withSourceMappedStacks(symbolicator, orgId, entries, rules), + mapsInPlay: Option.match(symbolicator, { + onNone: () => Effect.succeedSome(false), + onSome: (stacks) => stacks.sourceMapsKnown(orgId), + }), samples: (hashes) => warehouse.compiledQuery( tenant, @@ -221,17 +380,62 @@ export interface GroupingKeyReads { readonly spans: ( samples: ReadonlyArray, ) => Effect.Effect, E> + /** The samples with their stacks source-mapped; absent, every sample keys on its raw stack. */ + readonly sourceMapped?: ( + entries: ReadonlyArray, + rules: CompiledGroupingRules, + ) => Effect.Effect> + /** Whether the org has source maps, `None` when the lookup failed; absent, it has none. */ + readonly mapsInPlay?: Effect.Effect> } const storedKeys = (db: MapleDb, orgId: OrgId, hashes: ReadonlyArray) => Effect.forEach(Arr.chunksOf(hashes, CHUNK), (chunk) => db.run( PG.from(ErrorGroupingKeys) - .select("fingerprintHash", "groupingKey", "keyVersion", "configDigest", "pinned") + .select("fingerprintHash", "groupingKey", "keyVersion", "configDigest", "pinned", "rule") .where(($) => [$.orgId.eq(orgId), $.fingerprintHash.in_(...chunk)]), ), ).pipe(Effect.map(Arr.flatten)) +/** + * When each hash was first seen, from the rows the tick keeps for it: its candidate, its issue, + * or its alias on another issue. A hash with none is being seen for the first time. + */ +const firstSeenOf = ( + db: MapleDb, + orgId: OrgId, + hashes: ReadonlyArray, +): Effect.Effect, MapleDbError> => + Effect.forEach(Arr.chunksOf(hashes, CHUNK), (chunk) => + Effect.all([ + db.run( + PG.from(ErrorFingerprintCandidates) + .select("fingerprintHash", "firstSeenAt") + .where(($) => [$.orgId.eq(orgId), $.fingerprintHash.in_(...chunk)]), + ), + db.run( + PG.from(ErrorIssues) + .select("fingerprintHash", "firstSeenAt") + .where(($) => [$.orgId.eq(orgId), $.fingerprintHash.in_(...chunk)]), + ), + db.run( + PG.from(ErrorIssueFingerprints) + .select(($) => ({ fingerprintHash: $.fingerprintHash, firstSeenAt: $.createdAt })) + .where(($) => [$.orgId.eq(orgId), $.fingerprintHash.in_(...chunk)]), + ), + ]), + ).pipe( + Effect.map((chunks) => + Arr.reduce(Arr.flatten(Arr.flatten(chunks)), new Map(), (seen, row) => + seen.set( + row.fingerprintHash, + Math.min(seen.get(row.fingerprintHash) ?? row.firstSeenAt, row.firstSeenAt), + ), + ), + ), + ) + /** * Key the hashes that have no current key yet, then return, for each hash, the other * hashes sharing its key. The tick treats those siblings as it treats the hashes a @@ -254,22 +458,106 @@ export const resolveGroupingSiblings = ( ): Effect.Effect>> => Effect.gen(function* () { const { orgId, nowMs } = input - const configDigest = input.grouping.digest - const isCurrent = (row: { readonly keyVersion: number; readonly configDigest: string }) => - row.keyVersion === GROUPING_KEY_VERSION && row.configDigest === configDigest const hashes = Arr.dedupe(input.hashes) if (hashes.length === 0) return new Map() + const mapsKnown = reads.mapsInPlay === undefined ? Option.some(false) : yield* reads.mapsInPlay + const mapsInPlay = Option.getOrElse(mapsKnown, () => false) + // Whether the org has maps is part of the digest, so a first upload re-keys its keys once. + // An org without maps keeps the rules digest as it was. + const withMaps = `${input.grouping.digest}+source-maps` + const configDigest = mapsInPlay ? withMaps : input.grouping.digest + // A failed lookup decides nothing: a key under either maps bit stays current this tick. + const currentDigests = Option.isSome(mapsKnown) ? [configDigest] : [input.grouping.digest, withMaps] + const isCurrent = (row: { readonly keyVersion: number; readonly configDigest: string }) => + row.keyVersion === GROUPING_KEY_VERSION && Arr.contains(currentDigests, row.configDigest) const stored = yield* dbRun((tx) => storedKeys(tx, orgId, hashes)) const current = new Set(Arr.map(Arr.filter(stored, isCurrent), (row) => row.fingerprintHash)) // Hashes never keyed first (likely new issues), then stale keys after a rules change. const storedHashes = new Set(Arr.map(stored, (row) => row.fingerprintHash)) + const neverKeyed = Arr.filter(hashes, (hash) => !storedHashes.has(hash)) + // Over the cap, the order decides who waits. Hashes held past their grace window come first, + // up to half the slots (a hash whose span never turns up stays in that group, so it must not + // hold every slot); then first sightings; then hashes still held and the rest of the expired, + // each in an order that rotates every minute so none is stuck behind the same prefix. + // Under the cap everything fits and nothing more is read. + const overCap = neverKeyed.length > GROUPING_KEYS_PER_TICK + const earlierSeen = overCap + ? yield* dbRun((tx) => firstSeenOf(tx, orgId, neverKeyed)) + : new Map() + const graceOver = (hash: string) => nowMs - (earlierSeen.get(hash) ?? nowMs) >= MAP_PENDING_GRACE_MS + const minute = Math.floor(nowMs / 60_000) + const rotate = (list: ReadonlyArray) => { + const turn = list.length === 0 ? 0 : minute % list.length + return [...list.slice(turn), ...list.slice(0, turn)] + } + const expired = rotate(Arr.filter(neverKeyed, (hash) => earlierSeen.has(hash) && graceOver(hash))) + const held = rotate(Arr.filter(neverKeyed, (hash) => earlierSeen.has(hash) && !graceOver(hash))) + const expiredShare = Math.floor(GROUPING_KEYS_PER_TICK / 2) + // Stale keys (a rules change, a first upload) get up to a quarter, so a storm of new hashes + // cannot stall re-keying; any share a group leaves unused goes to the groups after it. + const staleShare = Math.floor(GROUPING_KEYS_PER_TICK / 4) + const stale = rotate(Arr.filter(hashes, (hash) => storedHashes.has(hash) && !current.has(hash))) const unkeyed = [ - ...Arr.filter(hashes, (hash) => !storedHashes.has(hash)), - ...Arr.filter(hashes, (hash) => storedHashes.has(hash) && !current.has(hash)), + ...stale.slice(0, staleShare), + ...expired.slice(0, expiredShare), + ...rotate(Arr.filter(neverKeyed, (hash) => !earlierSeen.has(hash))), + ...held, + ...expired.slice(expiredShare), + ...stale.slice(staleShare), ].slice(0, GROUPING_KEYS_PER_TICK) const samples = unkeyed.length === 0 ? [] : yield* reads.samples(unkeyed) const spans = samples.length === 0 ? [] : yield* reads.spans(samples) - const computed = computeGroupingKeys(samples, spans, input.grouping.rules) + const entries = computeSampleInputs(samples, spans) + const mapped = + reads.sourceMapped === undefined || entries.length === 0 + ? entries + : yield* reads.sourceMapped(entries, input.grouping.rules) + // A never-keyed hash whose frames found no map yet (or whose lookup failed) waits, up to the + // grace window from its first sighting: keyed now on its raw frames, it would never be keyed + // again. Past the window it keys on what it has. A hash with no row yet is a first sighting. + // A hash with a stored key whose lookup failed or whose map is pending keeps that key this tick: re-keying it on + // raw frames could overwrite a good mapped key. + const neverKeyedSet = new Set(neverKeyed) + const waits = (entry: SampleInput) => + neverKeyedSet.has(entry.fingerprintHash) && + (entry.mapPending === true || entry.lookupFailed === true) + const pending = Arr.filter(mapped, waits) + const pendingUnknown = Arr.filter( + Arr.map(pending, (entry) => entry.fingerprintHash), + (hash) => !earlierSeen.has(hash), + ) + const pendingSeen = + pendingUnknown.length === 0 + ? earlierSeen + : new Map([...earlierSeen, ...(yield* dbRun((tx) => firstSeenOf(tx, orgId, pendingUnknown)))]) + // The stack mapped, yet its frames gave no identity to key on (no name, no source text), so + // the key fell back to raw frames: a stored key, maybe a good mapped one, is not replaced by it. + const mappedUnusable = (entry: SampleInput) => { + if (entry.input.symbolicatedStack === undefined) return false + const rule = groupingParts(entry.input, input.grouping.rules).rule + return rule === "frames" || rule === "type-function" + } + // The vetoes protect a stored key from a worse one, never a rules change: a stored mapped key + // is kept against an unmapped or identity-less sample; a raw key only waits for a pending or + // failed lookup when the org's rules are unchanged (the maps bit alone made it stale). + const storedOf = new Map(Arr.map(stored, (row) => [row.fingerprintHash, row] as const)) + const rulesChanged = (row: { readonly keyVersion: number; readonly configDigest: string }) => + row.keyVersion !== GROUPING_KEY_VERSION || + Str.replace(/\+source-maps$/u, "")(row.configDigest) !== input.grouping.digest + const keepsStored = (entry: SampleInput) => { + const row = storedOf.get(entry.fingerprintHash) + if (row === undefined) return false + const unsure = entry.lookupFailed === true || entry.mapPending === true + return row.rule === "source-mapped" || row.rule === "source-mapped-function" + ? unsure || mappedUnusable(entry) + : unsure && !rulesChanged(row) + } + const ready = Arr.filter(mapped, (entry) => + waits(entry) + ? nowMs - (pendingSeen.get(entry.fingerprintHash) ?? nowMs) >= MAP_PENDING_GRACE_MS + : !keepsStored(entry), + ) + const computed = computeGroupingKeys(ready, input.grouping.rules) if (computed.length > 0) { yield* dbRun((tx) => Effect.forEach( @@ -366,7 +654,7 @@ export const resolveGroupingSiblings = ( $.orgId.eq(orgId), $.groupingKey.in_(...chunk), $.keyVersion.eq(GROUPING_KEY_VERSION), - $.configDigest.eq(configDigest), + $.configDigest.in_(...currentDigests), $.pinned.eq(false), ]) .groupBy("groupingKey"), diff --git a/packages/backend/src/services/org/OrganizationDeletionService.test.ts b/packages/backend/src/services/org/OrganizationDeletionService.test.ts index dffb7baec9..d58a0bc39d 100644 --- a/packages/backend/src/services/org/OrganizationDeletionService.test.ts +++ b/packages/backend/src/services/org/OrganizationDeletionService.test.ts @@ -351,6 +351,7 @@ describe("OrganizationDeletionService.delete", () => { assert.deepStrictEqual(Arr.dedupe(Arr.map(queued, (row) => row.kind)), [ "chat_session", "replay_blobs", + "source_maps", "warehouse", ]) assert.strictEqual(yield* countOrgRows(testDb, "investigations", "org_id", ORG_A), 0) diff --git a/packages/backend/src/services/org/org-erasure.ts b/packages/backend/src/services/org/org-erasure.ts index 14f35ba739..7f61154e42 100644 --- a/packages/backend/src/services/org/org-erasure.ts +++ b/packages/backend/src/services/org/org-erasure.ts @@ -7,10 +7,16 @@ import type { OrgErasureKind } from "@maple/domain/org-erasure" import { WAREHOUSE_ERASURE_TARGETS, warehouseErasureRank } from "@maple/domain/tinybird/org-erasure-plan" import type { OrgId } from "@maple/primitives" import { Array as Arr, Clock, Duration, Effect, Option, Schema } from "effect" -import { ChatSessions, ReplayBlobEraser } from "@maple/backend/platform/bindings" +import { + ChatSessions, + type ObjectPrefixEraser, + ReplayBlobEraser, + SourceMapEraser, +} from "@maple/backend/platform/bindings" import { Database, type DatabaseApi } from "@maple/backend/platform/DatabaseLive" import { describeCause } from "@maple/backend/platform/describe-cause" import { WarehouseDeleteClient } from "@maple/backend/services/warehouse/WarehouseDeleteClient" +import { sourceMapOrgPrefix } from "@maple/backend/services/sourcemaps/source-map-files" /** * Erasing what a deleted organization left outside Postgres: its agent conversations (one @@ -52,11 +58,12 @@ const insertErasures = ( { discard: true }, ) -/** Queue the erasures that need no rows read: replay prefix and warehouse datasources. Re-queuing is a no-op. */ +/** Queue the erasures that need no rows read: object prefixes and warehouse datasources. Re-queuing is a no-op. */ export const queueOrgErasures = (db: MapleDb, orgId: OrgId, now: number) => Effect.gen(function* () { const targets: ReadonlyArray = [ ["replay_blobs", replayPrefix(orgId)], + ["source_maps", sourceMapOrgPrefix(orgId)], ...Arr.map(WAREHOUSE_ERASURE_TARGETS, (target) => ["warehouse", target.datasource] as const), ] yield* insertErasures(db, orgId, now, targets) @@ -166,23 +173,30 @@ const eraseChatSession = (row: OrgErasureRow): Effect.Effect => - Effect.gen(function* () { - const eraser = yield* Effect.serviceOption(ReplayBlobEraser) - if (Option.isNone(eraser)) return DONE - const deletePage = eraser.value.deletePage - const loop = (pagesLeft: number): Effect.Effect => - deletePage(row.target).pipe( - Effect.mapError( - (error) => new OrgErasureError({ message: error.message, cause: error.cause }), - ), - Effect.flatMap((deleted) => { - if (deleted === 0) return Effect.succeed("done") - return pagesLeft <= 1 ? Effect.succeed("more") : loop(pagesLeft - 1) - }), - ) - return yield* loop(REPLAY_PAGES_PER_TICK) - }) +/** Deletes the objects under the row's prefix, a bounded number of listing pages per tick. */ +const erasePrefix = ( + row: OrgErasureRow, + eraser: Option.Option, +): Effect.Effect => { + // No binding means this host never stored such objects, so there is nothing to erase. + if (Option.isNone(eraser)) return Effect.succeed(DONE) + const deletePage = eraser.value.deletePage + const loop = (pagesLeft: number): Effect.Effect => + deletePage(row.target).pipe( + Effect.mapError((error) => new OrgErasureError({ message: error.message, cause: error.cause })), + Effect.flatMap((deleted) => { + if (deleted === 0) return Effect.succeed("done") + return pagesLeft <= 1 ? Effect.succeed("more") : loop(pagesLeft - 1) + }), + ) + return loop(REPLAY_PAGES_PER_TICK) +} + +const eraseReplayBlobs = (row: OrgErasureRow) => + Effect.flatMap(Effect.serviceOption(ReplayBlobEraser), (eraser) => erasePrefix(row, eraser)) + +const eraseSourceMaps = (row: OrgErasureRow) => + Effect.flatMap(Effect.serviceOption(SourceMapEraser), (eraser) => erasePrefix(row, eraser)) const setJob = (database: DatabaseApi, id: string, jobId: string | null) => database.execute((db) => @@ -224,6 +238,8 @@ const eraseTarget = (row: OrgErasureRow, database: DatabaseApi) => { return eraseChatSession(row) case "replay_blobs": return eraseReplayBlobs(row) + case "source_maps": + return eraseSourceMaps(row) case "warehouse": return eraseWarehouseRows(row, database) } diff --git a/packages/backend/src/services/sourcemaps/SourceMapReader.ts b/packages/backend/src/services/sourcemaps/SourceMapReader.ts new file mode 100644 index 0000000000..3079e136c1 --- /dev/null +++ b/packages/backend/src/services/sourcemaps/SourceMapReader.ts @@ -0,0 +1,171 @@ +import * as PG from "@maple-dev/effect-orm/postgres" +import { SourceMapFiles, type SourceMapFileRow } from "@maple/db/tables" +import { SourceMapStorageError } from "@maple/domain/http" +import type { OrgId, SourceMapFileId } from "@maple/primitives" +import { Array as Arr, Clock, Context, Duration, Effect, Layer, Option, String as Str } from "effect" +import { type ObjectStoreError, SourceMapReadBucket } from "@maple/backend/platform/bindings" +import { Database, type DatabaseError } from "@maple/backend/platform/DatabaseLive" +import { describeCause } from "@maple/backend/platform/describe-cause" +import { makeDbExecute } from "@maple/backend/platform/db-execute" +import { frameUrlPath } from "@maple/domain/errors/js-stack" +import { matchFrames } from "./source-map-files" + +/** `last_used_at` is written at most this often per file; retention allows for it. */ +export const SOURCE_MAP_TOUCH_INTERVAL = Duration.days(1) +/** Rows for the requested paths only, newest first; past this many, older builds of a path drop. */ +const RELEASE_FILES_LIMIT = 2000 + +/** `a/b/c.js` -> `a/b/c.js`, `b/c.js`, `c.js`: every stored path `urlMatchesMinifiedPath` accepts. */ +export const pathSuffixes = (url: string): ReadonlyArray => { + const segments = Str.split("/")(frameUrlPath(url)) + return Arr.filter( + Arr.map(segments, (_, i) => Arr.join(segments.slice(i), "/")), + (suffix) => suffix !== "", + ) +} + +export interface SourceMapFrameLookup { + readonly orgId: OrgId + /** Frame URL to the debug id the SDK recorded for it (`maple.exception.debug_ids`). */ + readonly debugIds: ReadonlyMap + readonly serviceName: string | null | undefined + readonly version: string | null | undefined + readonly urls: ReadonlyArray +} + +/** What symbolication needs: finding and reading stored maps. Writes only `last_used_at`. */ +export interface SourceMapReaderApi { + /** Whether the org has stored any source map. */ + readonly hasAny: (orgId: OrgId) => Effect.Effect + /** The stored file for each frame URL that has one: debug id first, then service + version + path. */ + readonly findForFrames: ( + lookup: SourceMapFrameLookup, + ) => Effect.Effect, SourceMapStorageError> + /** The map JSON, or `None` when its object is gone. */ + readonly load: (row: SourceMapFileRow) => Effect.Effect, SourceMapStorageError> + /** Marks files used now, at most once a day each, which keeps them from expiring. */ + readonly touch: ( + orgId: OrgId, + ids: ReadonlyArray, + ) => Effect.Effect +} + +export const toSourceMapStorageError = (error: DatabaseError | ObjectStoreError) => + new SourceMapStorageError({ + message: error.message, + ...(describeCause(error.cause) === undefined ? undefined : { cause: describeCause(error.cause) }), + }) + +export class SourceMapReader extends Context.Service()( + "@maple/backend/services/sourcemaps/SourceMapReader", + { + make: Effect.gen(function* () { + const database = yield* Database + const bucket = yield* SourceMapReadBucket + const dbExecute = makeDbExecute(database, "SourceMapReader", toSourceMapStorageError) + + const hasAny = Effect.fn("SourceMapReader.hasAny")(function* (orgId: OrgId) { + yield* Effect.annotateCurrentSpan({ orgId }) + const rows = yield* dbExecute((db) => + db.run( + PG.from(SourceMapFiles) + .select("id") + .where(($) => [$.orgId.eq(orgId)]) + .limit(1), + ), + ) + return rows.length > 0 + }) + + const findForFrames = Effect.fn("SourceMapReader.findForFrames")(function* ( + lookup: SourceMapFrameLookup, + ) { + const { orgId, serviceName, version } = lookup + yield* Effect.annotateCurrentSpan({ + orgId, + "maple.source_map.frame_urls": lookup.urls.length, + }) + const debugIds = Arr.dedupe( + Arr.map( + Arr.filter(Array.from(lookup.debugIds.values()), (id) => id.length > 0), + Str.toLowerCase, + ), + ) + const byDebugId = + debugIds.length === 0 + ? [] + : yield* dbExecute((db) => + db.run( + PG.from(SourceMapFiles) + .select() + .where(($) => [$.orgId.eq(orgId), $.debugId.in_(...debugIds)]), + ), + ) + // Only the stored paths a frame URL can match: its path and each suffix after a `/`. + const candidatePaths = Arr.dedupe(Arr.flatMap(lookup.urls, pathSuffixes)) + const hasRelease = + serviceName != null && + version != null && + serviceName !== "" && + version !== "" && + candidatePaths.length > 0 + const releaseQuery = (withDebugId: boolean) => + dbExecute((db) => + db.run( + PG.from(SourceMapFiles) + .select() + .where(($) => [ + $.orgId.eq(orgId), + $.serviceName.eq(serviceName ?? ""), + $.version.eq(version ?? ""), + $.minifiedPath.in_(...candidatePaths), + withDebugId ? $.debugId.isNotNull() : $.debugId.isNull(), + ]) + .orderBy(($) => [[$.createdAt, "desc"]]) + .limit(RELEASE_FILES_LIMIT), + ), + ) + // The id-less maps (one per path, by the unique index) win a path, so they are read + // apart from the debug-id builds, which can be many and only fill in paths they lack. + const releaseFiles = hasRelease + ? [...(yield* releaseQuery(false)), ...(yield* releaseQuery(true))] + : [] + const matches = matchFrames(lookup.urls, lookup.debugIds, byDebugId, releaseFiles) + yield* Effect.annotateCurrentSpan({ "maple.source_map.matched": matches.size }) + return matches + }) + + const load = Effect.fn("SourceMapReader.load")(function* (row: SourceMapFileRow) { + yield* Effect.annotateCurrentSpan({ orgId: row.orgId, "maple.source_map.id": row.id }) + const bytes = yield* bucket + .getBytes(row.objectKey) + .pipe(Effect.mapError(toSourceMapStorageError)) + return Option.map(bytes, (value) => new TextDecoder().decode(value)) + }) + + const touch = Effect.fn("SourceMapReader.touch")(function* ( + orgId: OrgId, + ids: ReadonlyArray, + ) { + if (ids.length === 0) return + const now = yield* Clock.currentTimeMillis + const staleBefore = now - Duration.toMillis(SOURCE_MAP_TOUCH_INTERVAL) + yield* dbExecute((db) => + db.run( + PG.update(SourceMapFiles) + .set({ lastUsedAt: now }) + .where(($) => [ + $.orgId.eq(orgId), + PG.inList($.id, Arr.dedupe(ids)), + PG.or($.lastUsedAt.isNull(), $.lastUsedAt.lt(staleBefore)), + ]), + ), + ) + }) + + return { hasAny, findForFrames, load, touch } satisfies SourceMapReaderApi + }), + }, +) { + static readonly layer = Layer.effect(this, this.make) +} diff --git a/packages/backend/src/services/sourcemaps/SourceMapService.test.ts b/packages/backend/src/services/sourcemaps/SourceMapService.test.ts new file mode 100644 index 0000000000..51b8dc4be7 --- /dev/null +++ b/packages/backend/src/services/sourcemaps/SourceMapService.test.ts @@ -0,0 +1,742 @@ +import { afterEach, describe, expect, it } from "@effect/vitest" +import { OrgId } from "@maple/domain/http" +import { Array as Arr, Duration, Effect, Layer, Option, Order, Schema, String as Str } from "effect" +import { TestClock } from "effect/testing" +import * as PG from "@maple-dev/effect-orm/postgres" +import { SourceMapFiles } from "@maple/db/tables" +import { SOURCE_MAP_MAX_BYTES } from "@maple/domain/http" +import { SourceMapFileId } from "@maple/primitives" +import { inMemoryObjectStore, sourceMapBucketLayer } from "@maple/backend/platform/bindings" +import { Database } from "@maple/backend/platform/DatabaseLive" +import { cleanupTestDbs, createTestDb, type TestDb } from "@maple/backend/testing/test-pglite" +import { SourceMapReader } from "./SourceMapReader" +import { claimExpired, SOURCE_MAP_RETENTION, SourceMapService } from "./SourceMapService" + +const createdDbs: TestDb[] = [] +afterEach(() => cleanupTestDbs(createdDbs)) + +const ORG = Schema.decodeSync(OrgId)("org_maps") +const OTHER_ORG = Schema.decodeSync(OrgId)("org_maps_other") +const DEBUG_ID = "6c5e2b1a-1f2e-4d3c-8b7a-0123456789ab" + +const makeHarness = (database: Layer.Layer = createTestDb(createdDbs).layer) => { + const objects = new Map() + const store = inMemoryObjectStore(objects) + const layer = Layer.mergeAll( + Layer.effect(SourceMapService, SourceMapService.make), + Layer.effect(SourceMapReader, SourceMapReader.make), + ).pipe(Layer.provideMerge(database), Layer.provide(sourceMapBucketLayer(store))) + return { objects, store, layer } +} + +const mapBytes = (fields: Record = {}) => + new TextEncoder().encode( + JSON.stringify({ version: 3, sources: ["src/a.ts"], names: [], mappings: "AAAA", ...fields }), + ) + +describe("SourceMapService.upload", () => { + it.effect("replaces the file with the same debug id, object included", () => { + const { objects, layer } = makeHarness() + return Effect.gen(function* () { + const service = yield* SourceMapService + const first = yield* service.upload(ORG, { + bytes: mapBytes(), + minifiedPath: "assets/a.js", + debugId: Str.toUpperCase(DEBUG_ID), + }) + const second = yield* service.upload(ORG, { + bytes: mapBytes({ sourcesContent: ["export const a = 1"] }), + minifiedPath: "/assets/a-renamed.js", + debugId: DEBUG_ID, + }) + yield* service.upload(OTHER_ORG, { + bytes: mapBytes(), + minifiedPath: "assets/a.js", + debugId: DEBUG_ID, + }) + + const rows = yield* service.list(ORG, { limit: 10, offset: 0 }) + expect( + Arr.map(rows, (row) => [row.id, row.debugId, row.minifiedPath, row.hasSourcesContent]), + ).toEqual([[second.id, DEBUG_ID, "assets/a-renamed.js", true]]) + expect(objects.has(first.objectKey)).toBe(false) + const reader = yield* SourceMapReader + expect(Option.getOrNull(yield* reader.load(second))).toContain("export const a = 1") + expect(objects.size).toBe(2) + }).pipe(Effect.provide(layer)) + }) + + it.effect("replaces by service, version and path when there is no debug id", () => { + const { objects, layer } = makeHarness() + return Effect.gen(function* () { + const service = yield* SourceMapService + const release = { serviceName: "web", version: "1.2.0" } + const first = yield* service.upload(ORG, { + bytes: mapBytes(), + minifiedPath: "assets/a.js", + ...release, + }) + yield* service.upload(ORG, { bytes: mapBytes(), minifiedPath: "assets/b.js", ...release }) + yield* service.upload(ORG, { + bytes: mapBytes(), + minifiedPath: "assets/a.js", + serviceName: "web", + version: "1.3.0", + }) + const replacement = yield* service.upload(ORG, { + bytes: mapBytes(), + minifiedPath: "./assets/a.js", + ...release, + }) + + const rows = yield* service.list(ORG, { + serviceName: "web", + version: "1.2.0", + limit: 10, + offset: 0, + }) + expect( + Arr.sort( + Arr.map(rows, (row) => row.minifiedPath), + Order.String, + ), + ).toEqual(["assets/a.js", "assets/b.js"]) + expect(Arr.some(rows, (row) => row.id === replacement.id)).toBe(true) + expect(objects.has(first.objectKey)).toBe(false) + }).pipe(Effect.provide(layer)) + }) + + it.effect("replaces a concurrent upload of the same map that committed first", () => { + const objects = new Map() + const winnerId = Schema.decodeSync(SourceMapFileId)("0f0e0d0c-0b0a-4908-8706-050403020100") + const winnerKey = `v1/${ORG}/${winnerId}` + const insertWinner = PG.insertInto(SourceMapFiles).values({ + id: winnerId, + orgId: ORG, + debugId: DEBUG_ID, + serviceName: null, + version: null, + minifiedPath: "assets/a.js", + sizeBytes: 1, + hasSourcesContent: false, + objectKey: winnerKey, + createdAt: 0, + lastUsedAt: null, + }) + const state = { raced: false } + // The first row write loses the race: the other upload's row lands, then ours hits the + // unique index (a real 23505 from Postgres). + const racing = Layer.effect( + Database, + Effect.map(Database, (database) => ({ + ...database, + execute: (fn: Parameters>[0]) => + Effect.suspend(() => { + if (state.raced) return database.execute(fn) + state.raced = true + objects.set(winnerKey, mapBytes()) + return database + .execute((db) => db.run(insertWinner)) + .pipe( + Effect.orDie, + Effect.andThen(database.execute((db) => db.run(insertWinner))), + Effect.andThen(database.execute(fn)), + ) + }), + })), + ).pipe(Layer.provide(createTestDb(createdDbs).layer)) + const layer = Layer.mergeAll( + Layer.effect(SourceMapService, SourceMapService.make), + Layer.effect(SourceMapReader, SourceMapReader.make), + ).pipe(Layer.provide(racing), Layer.provide(sourceMapBucketLayer(inMemoryObjectStore(objects)))) + return Effect.gen(function* () { + const service = yield* SourceMapService + const row = yield* service.upload(ORG, { + bytes: mapBytes(), + minifiedPath: "assets/a.js", + debugId: DEBUG_ID, + }) + expect(state.raced).toBe(true) + const rows = yield* service.list(ORG, { limit: 10, offset: 0 }) + expect(Arr.map(rows, (r) => r.id)).toEqual([row.id]) + expect(objects.has(winnerKey)).toBe(false) + expect(objects.has(row.objectKey)).toBe(true) + }).pipe(Effect.provide(layer)) + }) + + it.effect("keeps the uploaded object when the row write fails, for the orphan sweep", () => { + const objects = new Map() + const other = PG.insertInto(SourceMapFiles).values({ + id: Schema.decodeSync(SourceMapFileId)("0f0e0d0c-0b0a-4908-8706-050403020101"), + orgId: OTHER_ORG, + debugId: null, + serviceName: "web", + version: "1", + minifiedPath: "other.js", + sizeBytes: 1, + hasSourcesContent: false, + objectKey: "v1/other", + createdAt: 0, + lastUsedAt: null, + }) + // Every row write fails (a duplicate key), as a lost commit ack would look to the caller. + const failing = Layer.effect( + Database, + Effect.map(Database, (database) => ({ + ...database, + execute: (fn: Parameters>[0]) => + database + .execute((db) => db.run(other)) + .pipe( + Effect.ignore, + Effect.andThen(database.execute((db) => db.run(other))), + Effect.andThen(database.execute(fn)), + ), + })), + ).pipe(Layer.provide(createTestDb(createdDbs).layer)) + const layer = Layer.effect(SourceMapService, SourceMapService.make).pipe( + Layer.provide(failing), + Layer.provide(sourceMapBucketLayer(inMemoryObjectStore(objects))), + ) + return Effect.gen(function* () { + const service = yield* SourceMapService + const error = yield* service + .upload(ORG, { bytes: mapBytes(), minifiedPath: "assets/a.js", debugId: DEBUG_ID }) + .pipe(Effect.flip) + expect(error._tag).toBe("@maple/http/sourcemaps/SourceMapStorageError") + expect(objects.size).toBe(1) + }).pipe(Effect.provide(layer)) + }) + + it.effect("accepts a map whose ignore list is an array of source indexes", () => { + const { layer } = makeHarness() + return Effect.gen(function* () { + const service = yield* SourceMapService + const row = yield* service.upload(ORG, { + bytes: mapBytes({ ignoreList: [0], x_google_ignoreList: [0] }), + minifiedPath: "assets/a.js", + debugId: DEBUG_ID, + }) + expect(row.debugId).toBe(DEBUG_ID) + }).pipe(Effect.provide(layer)) + }) + + it.effect("adopts the debug id the map itself carries", () => { + const { layer } = makeHarness() + return Effect.gen(function* () { + const service = yield* SourceMapService + const row = yield* service.upload(ORG, { + bytes: mapBytes({ debug_id: DEBUG_ID }), + minifiedPath: "assets/a.js", + }) + expect(row.debugId).toBe(DEBUG_ID) + }).pipe(Effect.provide(layer)) + }) + + it.effect("keeps builds with their own debug ids apart on one release path", () => { + const { objects, layer } = makeHarness() + return Effect.gen(function* () { + const service = yield* SourceMapService + const path = { minifiedPath: "assets/main.js", serviceName: "web", version: "1.4.2" } + const releaseOnly = yield* service.upload(ORG, { bytes: mapBytes(), ...path }) + const first = yield* service.upload(ORG, { bytes: mapBytes(), debugId: DEBUG_ID, ...path }) + const second = yield* service.upload(ORG, { + bytes: mapBytes(), + debugId: "7d6f3c2b-2a3f-4e4d-9c8b-123456789abc", + ...path, + }) + const rows = yield* service.list(ORG, { limit: 10, offset: 0 }) + expect( + Arr.sort( + Arr.map(rows, (row) => row.id), + Order.String, + ), + ).toEqual(Arr.sort([releaseOnly.id, first.id, second.id], Order.String)) + expect(Arr.every([first, second, releaseOnly], (row) => objects.has(row.objectKey))).toBe(true) + }).pipe(Effect.provide(layer)) + }) + + it.effect("keeps the stored map when a replacement is not usable", () => { + const { objects, layer } = makeHarness() + return Effect.gen(function* () { + const service = yield* SourceMapService + const release = { minifiedPath: "assets/main.js", serviceName: "web", version: "2.4.0" } + const stored = yield* service.upload(ORG, { bytes: mapBytes(), ...release }) + const unusable = [ + mapBytes({ sources: undefined }), + mapBytes({ sources: [] }), + mapBytes({ sources: [1] }), + mapBytes({ ignoreList: {} }), + mapBytes({ x_google_ignoreList: [-1] }), + mapBytes({ mappings: undefined, sections: [{ offset: { line: 0 }, map: {} }] }), + ] + const errors = yield* Effect.forEach(unusable, (bytes) => + service.upload(ORG, { bytes, ...release }).pipe( + Effect.flip, + Effect.map((error) => error._tag), + ), + ) + expect(Arr.dedupe(errors)).toEqual(["@maple/http/sourcemaps/SourceMapInvalidError"]) + const rows = yield* service.list(ORG, { limit: 10, offset: 0 }) + expect(Arr.map(rows, (row) => row.id)).toEqual([stored.id]) + expect([...objects.keys()]).toEqual([stored.objectKey]) + }).pipe(Effect.provide(layer)) + }) + + it.effect("refuses an index map, keeping the stored one", () => { + const { objects, layer } = makeHarness() + return Effect.gen(function* () { + const service = yield* SourceMapService + const stored = yield* service.upload(ORG, { + bytes: mapBytes(), + minifiedPath: "assets/a.js", + debugId: DEBUG_ID, + }) + const section = { version: 3, sources: ["src/a.ts"], names: [], mappings: "AAAA" } + const indexMaps = [ + { version: 3, sections: [{ offset: { line: 0, column: 0 }, map: section }] }, + // A plain map with a stray `sections` field is still not a plain map. + { ...section, sections: null }, + ] + const errors = yield* Effect.forEach(indexMaps, (map) => + service + .upload(ORG, { + bytes: new TextEncoder().encode(JSON.stringify(map)), + minifiedPath: "assets/a.js", + debugId: DEBUG_ID, + }) + .pipe( + Effect.flip, + Effect.map((error) => [error._tag, error.message]), + ), + ) + expect(Arr.dedupe(Arr.map(errors, (e) => Arr.join(e, " ")))).toEqual([ + "@maple/http/sourcemaps/SourceMapInvalidError Index source maps are not supported; emit a regular map.", + ]) + const rows = yield* service.list(ORG, { limit: 10, offset: 0 }) + expect(Arr.map(rows, (row) => row.id)).toEqual([stored.id]) + expect([...objects.keys()]).toEqual([stored.objectKey]) + }).pipe(Effect.provide(layer)) + }) + + it.effect("rejects what is not a usable source map, storing nothing", () => { + const { objects, layer } = makeHarness() + return Effect.gen(function* () { + const service = yield* SourceMapService + const reject = (input: Parameters[1]) => + service.upload(ORG, input).pipe( + Effect.flip, + Effect.map((error) => [error._tag, "param" in error ? error.param : undefined]), + ) + const base = { minifiedPath: "assets/a.js", debugId: DEBUG_ID } + + expect(yield* reject({ ...base, bytes: new TextEncoder().encode("not json") })).toEqual([ + "@maple/http/sourcemaps/SourceMapInvalidError", + undefined, + ]) + expect(yield* reject({ ...base, bytes: mapBytes({ version: 2 }) })).toEqual([ + "@maple/http/sourcemaps/SourceMapInvalidError", + undefined, + ]) + expect( + yield* reject({ ...base, bytes: mapBytes({ mappings: undefined, sections: [] }) }), + ).toEqual(["@maple/http/sourcemaps/SourceMapInvalidError", undefined]) + expect(yield* reject({ ...base, bytes: mapBytes(), debugId: "not-a-uuid" })).toEqual([ + "@maple/http/sourcemaps/SourceMapInvalidError", + "debug_id", + ]) + expect( + yield* reject({ bytes: mapBytes(), minifiedPath: "assets/a.js", serviceName: "web" }), + ).toEqual(["@maple/http/sourcemaps/SourceMapInvalidError", "debug_id"]) + // 1,000 three-byte characters: under the length limit, over the index entry's bytes. + expect( + yield* reject({ + bytes: mapBytes(), + minifiedPath: `assets/${Str.repeat(1000)("\u20ac")}.js`, + serviceName: "web", + version: "1", + }), + ).toEqual(["@maple/http/sourcemaps/SourceMapInvalidError", "minified_path"]) + expect(yield* reject({ ...base, bytes: mapBytes(), minifiedPath: " / " })).toEqual([ + "@maple/http/sourcemaps/SourceMapInvalidError", + "minified_path", + ]) + expect(yield* reject({ ...base, bytes: new Uint8Array(SOURCE_MAP_MAX_BYTES + 1) })).toEqual([ + "@maple/http/sourcemaps/SourceMapTooLargeError", + undefined, + ]) + + expect(yield* service.list(ORG, { limit: 10, offset: 0 })).toEqual([]) + expect(objects.size).toBe(0) + }).pipe(Effect.provide(layer)) + }) +}) + +describe("SourceMapReader.findForFrames", () => { + it.effect("prefers the debug id, then the release path at a slash boundary", () => { + const { layer } = makeHarness() + return Effect.gen(function* () { + const service = yield* SourceMapService + const reader = yield* SourceMapReader + const release = { serviceName: "web", version: "1.2.0" } + const byDebugId = yield* service.upload(ORG, { + bytes: mapBytes(), + minifiedPath: "elsewhere/main.js", + debugId: DEBUG_ID, + }) + const byPath = yield* service.upload(ORG, { + bytes: mapBytes(), + minifiedPath: "assets/main.js", + ...release, + }) + const deeper = yield* service.upload(ORG, { + bytes: mapBytes(), + minifiedPath: "v2/assets/main.js", + ...release, + }) + yield* service.upload(ORG, { bytes: mapBytes(), minifiedPath: "vendor.js", ...release }) + + const withDebugId = "https://cdn.test/assets/main.js" + const nested = "https://cdn.test/static/v2/assets/main.js?v=3" + const plain = "https://cdn.test/static/assets/main.js" + const boundary = "https://cdn.test/static/my-vendor.js" + const otherDebugId = "https://cdn.test/assets/other.js" + const matches = yield* reader.findForFrames({ + orgId: ORG, + debugIds: new Map([ + [withDebugId, Str.toUpperCase(DEBUG_ID)], + [otherDebugId, "00000000-0000-4000-8000-000000000000"], + ]), + ...release, + urls: [withDebugId, nested, plain, boundary, otherDebugId], + }) + expect(matches.get(withDebugId)?.id).toBe(byDebugId.id) + expect(matches.get(nested)?.id).toBe(deeper.id) + expect(matches.get(plain)?.id).toBe(byPath.id) + expect(matches.has(boundary)).toBe(false) + expect(matches.has(otherDebugId)).toBe(false) + + const otherOrg = yield* reader.findForFrames({ + orgId: OTHER_ORG, + debugIds: new Map([[withDebugId, DEBUG_ID]]), + ...release, + urls: [withDebugId, plain], + }) + expect(otherOrg.size).toBe(0) + }).pipe(Effect.provide(layer)) + }) + it.effect("on a shared release path, prefers the map without a debug id, else the newest", () => { + const { layer } = makeHarness() + return Effect.gen(function* () { + const service = yield* SourceMapService + const reader = yield* SourceMapReader + const release = { serviceName: "web", version: "1.2.0" } + const url = "https://cdn.test/assets/main.js" + const find = Effect.map( + reader.findForFrames({ orgId: ORG, debugIds: new Map(), ...release, urls: [url] }), + (matches) => matches.get(url)?.id, + ) + yield* service.upload(ORG, { + bytes: mapBytes(), + minifiedPath: "assets/main.js", + debugId: DEBUG_ID, + ...release, + }) + yield* TestClock.adjust(Duration.seconds(1)) + const newer = yield* service.upload(ORG, { + bytes: mapBytes(), + minifiedPath: "assets/main.js", + debugId: "7d6f3c2b-2a3f-4e4d-9c8b-123456789abc", + ...release, + }) + expect(yield* find).toBe(newer.id) + const releaseOnly = yield* service.upload(ORG, { + bytes: mapBytes(), + minifiedPath: "assets/main.js", + ...release, + }) + yield* TestClock.adjust(Duration.seconds(1)) + yield* service.upload(ORG, { + bytes: mapBytes(), + minifiedPath: "assets/main.js", + debugId: "8e7a4d3c-3b4a-4f5e-8d9c-23456789abcd", + ...release, + }) + expect(yield* find).toBe(releaseOnly.id) + }).pipe(Effect.provide(layer)) + }) + + it.effect("finds a release's map however many other maps the release has", () => { + const { layer } = makeHarness() + return Effect.gen(function* () { + const service = yield* SourceMapService + const reader = yield* SourceMapReader + const database = yield* Database + const release = { serviceName: "web", version: "9.0.0" } + // 2,100 maps of the same release for other files, stored first. + yield* database.execute((db) => + db.run( + PG.insertInto(SourceMapFiles).values( + Arr.makeBy(2100, (i) => ({ + id: Schema.decodeSync(SourceMapFileId)( + `00000000-0000-4000-8000-${Str.padStart(12, "0")(String(i))}`, + ), + orgId: ORG, + debugId: null, + serviceName: "web", + version: "9.0.0", + minifiedPath: `assets/chunk-${i}.js`, + sizeBytes: 1, + hasSourcesContent: false, + objectKey: `v1/${ORG}/chunk-${i}`, + createdAt: 0, + lastUsedAt: null, + })), + ), + ), + ) + const target = yield* service.upload(ORG, { + bytes: mapBytes(), + minifiedPath: "assets/zz-last.js", + ...release, + }) + const url = "https://cdn.test/static/assets/zz-last.js" + const matches = yield* reader.findForFrames({ + orgId: ORG, + debugIds: new Map(), + ...release, + urls: [url], + }) + expect(matches.get(url)?.id).toBe(target.id) + }).pipe(Effect.provide(layer)) + }) + + it.effect("picks a release path's id-less map over thousands of newer debug-id builds", () => { + const { layer } = makeHarness() + return Effect.gen(function* () { + const service = yield* SourceMapService + const reader = yield* SourceMapReader + const database = yield* Database + const release = { serviceName: "web", version: "9.1.0" } + const releaseOnly = yield* service.upload(ORG, { + bytes: mapBytes(), + minifiedPath: "assets/main.js", + ...release, + }) + yield* database.execute((db) => + db.run( + PG.insertInto(SourceMapFiles).values( + Arr.makeBy(2100, (i) => ({ + id: Schema.decodeSync(SourceMapFileId)( + `00000000-0000-4000-9000-${Str.padStart(12, "0")(String(i))}`, + ), + orgId: ORG, + debugId: `10000000-0000-4000-8000-${Str.padStart(12, "0")(String(i))}`, + serviceName: "web", + version: "9.1.0", + minifiedPath: "assets/main.js", + sizeBytes: 1, + hasSourcesContent: false, + objectKey: `v1/${ORG}/build-${i}`, + createdAt: Duration.toMillis(Duration.days(1)), + lastUsedAt: null, + })), + ), + ), + ) + const url = "https://cdn.test/assets/main.js" + const matches = yield* reader.findForFrames({ + orgId: ORG, + debugIds: new Map(), + ...release, + urls: [url], + }) + expect(matches.get(url)?.id).toBe(releaseOnly.id) + }).pipe(Effect.provide(layer)) + }) + + it.effect("ranks stored paths by what they match, a query in one never lengthening it", () => { + const { layer } = makeHarness() + return Effect.gen(function* () { + const service = yield* SourceMapService + const reader = yield* SourceMapReader + const release = { serviceName: "web", version: "1.2.0" } + const exact = yield* service.upload(ORG, { + bytes: mapBytes(), + minifiedPath: "assets/main.js", + ...release, + }) + yield* service.upload(ORG, { + bytes: mapBytes(), + minifiedPath: "main.js?cache=123456", + ...release, + }) + const url = "https://cdn.test/assets/main.js" + const matches = yield* reader.findForFrames({ + orgId: ORG, + debugIds: new Map(), + ...release, + urls: [url], + }) + expect(matches.get(url)?.id).toBe(exact.id) + }).pipe(Effect.provide(layer)) + }) + + it.effect("matches a stored path whose file name holds an encoded `#`", () => { + const { layer } = makeHarness() + return Effect.gen(function* () { + const service = yield* SourceMapService + const reader = yield* SourceMapReader + const release = { serviceName: "web", version: "1.2.0" } + const stored = yield* service.upload(ORG, { + bytes: mapBytes(), + minifiedPath: "https://cdn.test/assets/a%23b.js", + ...release, + }) + expect(stored.minifiedPath).toBe("assets/a#b.js") + const url = "https://cdn.test/assets/a%23b.js" + const matches = yield* reader.findForFrames({ + orgId: ORG, + debugIds: new Map(), + ...release, + urls: [url], + }) + expect(matches.get(url)?.id).toBe(stored.id) + }).pipe(Effect.provide(layer)) + }) + + it.effect("matches percent-encoded frame URLs to the decoded stored path", () => { + const { layer } = makeHarness() + return Effect.gen(function* () { + const service = yield* SourceMapService + const reader = yield* SourceMapReader + const release = { serviceName: "web", version: "1.2.0" } + const spaced = yield* service.upload(ORG, { + bytes: mapBytes(), + minifiedPath: "assets/my file.js", + ...release, + }) + const fromUrl = yield* service.upload(ORG, { + bytes: mapBytes(), + minifiedPath: "https://cdn.test/assets/%5Bid%5D-page.js", + ...release, + }) + expect(fromUrl.minifiedPath).toBe("assets/[id]-page.js") + + const encoded = "https://cdn.test/assets/my%20file.js" + const bracketed = "https://cdn.test/assets/%5Bid%5D-page.js" + const malformed = "https://cdn.test/assets/%E0%A4%A.js" + const matches = yield* reader.findForFrames({ + orgId: ORG, + debugIds: new Map(), + ...release, + urls: [encoded, bracketed, malformed], + }) + expect(matches.get(encoded)?.id).toBe(spaced.id) + expect(matches.get(bracketed)?.id).toBe(fromUrl.id) + expect(matches.has(malformed)).toBe(false) + }).pipe(Effect.provide(layer)) + }) +}) + +describe("SourceMapService.sweepExpired", () => { + it.effect("deletes files unused for 90 days, counting a touch as use", () => { + const { objects, layer } = makeHarness() + return Effect.gen(function* () { + const service = yield* SourceMapService + const stale = yield* service.upload(ORG, { + bytes: mapBytes(), + minifiedPath: "a.js", + debugId: DEBUG_ID, + }) + const used = yield* service.upload(ORG, { + bytes: mapBytes(), + minifiedPath: "b.js", + serviceName: "web", + version: "1", + }) + yield* TestClock.adjust(Duration.days(60)) + yield* (yield* SourceMapReader).touch(ORG, [used.id]) + yield* TestClock.adjust(Duration.days(31)) + const fresh = yield* service.upload(ORG, { + bytes: mapBytes(), + minifiedPath: "c.js", + serviceName: "web", + version: "1", + }) + + const deleted = yield* service.sweepExpired(Duration.toMillis(Duration.days(91))) + expect(deleted).toBe(1) + const left = yield* service.list(ORG, { limit: 10, offset: 0 }) + expect( + Arr.sort( + Arr.map(left, (row) => row.id), + Order.String, + ), + ).toEqual(Arr.sort([used.id, fresh.id], Order.String)) + expect(objects.has(stale.objectKey)).toBe(false) + + // A recorded use may be a day stale, so the used file gets that day too. + const used90 = Duration.toMillis(Duration.days(60)) + Duration.toMillis(SOURCE_MAP_RETENTION) + expect(yield* service.sweepExpired(used90 + Duration.toMillis(Duration.hours(12)))).toBe(0) + expect(yield* service.sweepExpired(used90 + Duration.toMillis(Duration.days(1)) + 1)).toBe(1) + }).pipe(Effect.provide(layer)) + }) +}) + +describe("claimExpired", () => { + it.effect("keeps a map whose use was recorded after the sweep selected it", () => { + const { objects, layer } = makeHarness() + return Effect.gen(function* () { + const service = yield* SourceMapService + const database = yield* Database + const touched = yield* service.upload(ORG, { + bytes: mapBytes(), + minifiedPath: "a.js", + debugId: DEBUG_ID, + }) + const idle = yield* service.upload(ORG, { + bytes: mapBytes(), + minifiedPath: "b.js", + serviceName: "web", + version: "1", + }) + yield* TestClock.adjust(Duration.days(91)) + const cutoff = Duration.toMillis(Duration.days(1)) + // Both were expired when selected; one is used before the claim runs. + yield* (yield* SourceMapReader).touch(ORG, [touched.id]) + const claimed = yield* claimExpired(database, [touched.id, idle.id], cutoff) + expect(claimed).toEqual([idle.objectKey]) + const left = yield* service.list(ORG, { limit: 10, offset: 0 }) + expect(Arr.map(left, (row) => row.id)).toEqual([touched.id]) + expect(objects.has(touched.objectKey)).toBe(true) + }).pipe(Effect.provide(layer)) + }) +}) + +describe("SourceMapService.sweepOrphans", () => { + it.effect("deletes day-old objects no row points at and keeps everything else", () => { + const { objects, store, layer } = makeHarness() + return Effect.gen(function* () { + const service = yield* SourceMapService + const kept = yield* service.upload(ORG, { + bytes: mapBytes(), + minifiedPath: "a.js", + debugId: DEBUG_ID, + }) + const orphanKey = `v1/${ORG}/1a2b3c4d-0000-4000-8000-000000000001` + const foreignKey = `v1/${ORG}/not-a-file-id` + yield* store.put(orphanKey, mapBytes(), "application/json") + yield* store.put(foreignKey, mapBytes(), "application/json") + yield* TestClock.adjust(Duration.days(2)) + const freshKey = `v1/${ORG}/1a2b3c4d-0000-4000-8000-000000000002` + yield* store.put(freshKey, mapBytes(), "application/json") + + expect(yield* service.sweepOrphans(Duration.toMillis(Duration.days(2)))).toBe(1) + expect(objects.has(orphanKey)).toBe(false) + expect(objects.has(kept.objectKey)).toBe(true) + expect(objects.has(foreignKey)).toBe(true) + expect(objects.has(freshKey)).toBe(true) + }).pipe(Effect.provide(layer)) + }) +}) diff --git a/packages/backend/src/services/sourcemaps/SourceMapService.ts b/packages/backend/src/services/sourcemaps/SourceMapService.ts new file mode 100644 index 0000000000..b5d77c4b49 --- /dev/null +++ b/packages/backend/src/services/sourcemaps/SourceMapService.ts @@ -0,0 +1,432 @@ +import { randomUUID } from "node:crypto" +import * as PG from "@maple-dev/effect-orm/postgres" +import { SourceMapFiles, type SourceMapFileRow } from "@maple/db/tables" +import { + SourceMapInvalidError, + SourceMapNotFoundError, + SourceMapStorageError, + SourceMapTooLargeError, +} from "@maple/domain/http" +import { type OrgId, SourceMapFileId } from "@maple/primitives" +import { Array as Arr, Clock, Context, Duration, Effect, Layer, Option, Schema, String as Str } from "effect" +import { SourceMapBucket, type WritableObjectStore } from "@maple/backend/platform/bindings" +import { Database, type DatabaseApi } from "@maple/backend/platform/DatabaseLive" +import { makeDbExecute } from "@maple/backend/platform/db-execute" +import { postgresSqlState } from "@maple/backend/platform/postgres-errors" +import { type SourceMapUpload, sourceMapObjectKey, validateSourceMapUpload } from "./source-map-files" +import { SOURCE_MAP_TOUCH_INTERVAL, toSourceMapStorageError as toStorageError } from "./SourceMapReader" + +/** + * A file unused this long is deleted, row and object. A recorded use may be up to a day stale + * (`SOURCE_MAP_TOUCH_INTERVAL`), so a used file gets that day on top. + */ +export const SOURCE_MAP_RETENTION = Duration.days(90) +const SWEEP_BATCH = 500 +const SWEEP_BATCHES_PER_TICK = 10 +/** An object this old with no row is an upload whose row never landed. */ +const ORPHAN_MIN_AGE = Duration.days(1) +/** Objects checked per tick; R2 lists at most 1000 per page. */ +const ORPHAN_PAGE = 1000 +const OBJECT_PREFIX = "v1/" +/** Where the orphan pass resumes; outside `v1/`, so it is never listed as a map. */ +const ORPHAN_CURSOR_KEY = "meta/orphan-sweep-cursor" + +export interface SourceMapListFilter { + readonly serviceName?: string | undefined + readonly version?: string | undefined + readonly debugId?: string | undefined + readonly limit: number + readonly offset: number +} + +export interface SourceMapServiceApi { + /** Stores the map, replacing the file with its debug id, else the id-less file at its release path. */ + readonly upload: ( + orgId: OrgId, + upload: SourceMapUpload, + ) => Effect.Effect< + SourceMapFileRow, + SourceMapInvalidError | SourceMapTooLargeError | SourceMapStorageError + > + /** Newest first; `limit` rows from `offset`. */ + readonly list: ( + orgId: OrgId, + filter: SourceMapListFilter, + ) => Effect.Effect, SourceMapStorageError> + readonly remove: ( + orgId: OrgId, + id: SourceMapFileId, + ) => Effect.Effect + /** Deletes files unused for 90 days; returns how many went. */ + readonly sweepExpired: (now: number) => Effect.Effect + /** Deletes objects at least a day old that no row points at; one listing page per call. */ + readonly sweepOrphans: (now: number) => Effect.Effect +} + +const UNIQUE_VIOLATION = "23505" + +/** A concurrent upload of the same identity committed first; the write is retried once. */ +class SourceMapRowConflict extends Schema.TaggedError()( + "@maple/backend/sourcemaps/SourceMapRowConflict", + { message: Schema.String }, +) {} + +const decodeFileId = Schema.decodeSync(SourceMapFileId) + +const deleteObjects = (bucket: WritableObjectStore, rows: ReadonlyArray) => + rows.length === 0 + ? Effect.void + : bucket.delete(Arr.map(rows, (row) => row.objectKey)).pipe(Effect.mapError(toStorageError)) + +/** + * Deletes the rows among `ids` still unused since before `cutoff`, returning their object keys. + * The predicate is checked in the delete itself, so a use recorded after selection keeps its row. + */ +export const claimExpired = ( + database: DatabaseApi, + ids: ReadonlyArray, + cutoff: number, +): Effect.Effect, SourceMapStorageError> => + ids.length === 0 + ? Effect.succeed([]) + : makeDbExecute( + database, + "SourceMapService", + toStorageError, + )((db) => + db.run( + PG.deleteFrom(SourceMapFiles) + .where(($) => [ + PG.inList($.id, ids), + PG.or( + $.lastUsedAt.lt(cutoff - Duration.toMillis(SOURCE_MAP_TOUCH_INTERVAL)), + PG.and($.lastUsedAt.isNull(), $.createdAt.lt(cutoff)), + ), + ]) + .crossTenant() + .returning("objectKey"), + ), + ).pipe(Effect.map((rows) => Arr.map(rows, (row) => row.objectKey))) + +/** + * One sweep over every org: rows are claimed first, then their objects deleted. An object whose + * delete fails has no row left, so the orphan sweep removes it a day later. + */ +const sweep = (database: DatabaseApi, bucket: WritableObjectStore, now: number) => { + const dbExecute = makeDbExecute(database, "SourceMapService", toStorageError) + const cutoff = now - Duration.toMillis(SOURCE_MAP_RETENTION) + const batch = (left: number, deleted: number): Effect.Effect => + Effect.gen(function* () { + const candidates = yield* dbExecute((db) => + db.run( + PG.from(SourceMapFiles) + .select("id") + .where(($) => [ + PG.or( + $.lastUsedAt.lt(cutoff - Duration.toMillis(SOURCE_MAP_TOUCH_INTERVAL)), + PG.and($.lastUsedAt.isNull(), $.createdAt.lt(cutoff)), + ), + ]) + .orderBy(($) => [[$.createdAt, "asc"]]) + .limit(SWEEP_BATCH) + .crossTenant(), + ), + ) + if (candidates.length === 0) return deleted + const claimed = yield* claimExpired( + database, + Arr.map(candidates, (row) => row.id), + cutoff, + ) + if (claimed.length > 0) { + yield* bucket.delete(claimed).pipe( + Effect.tapError((error) => + Effect.logWarning( + "Expired source map objects were not deleted; the orphan sweep will", + ).pipe(Effect.annotateLogs({ count: claimed.length, message: error.message })), + ), + Effect.ignore, + ) + } + const total = deleted + claimed.length + return candidates.length < SWEEP_BATCH || left <= 1 ? total : yield* batch(left - 1, total) + }) + return batch(SWEEP_BATCHES_PER_TICK, 0) +} + +const decodeFileIdOption = Schema.decodeUnknownOption(SourceMapFileId) + +/** + * One page of the bucket, resuming where the last tick stopped: objects older than a day whose + * row is missing are deleted. Those are uploads whose isolate died between the object and the + * row, or replaced objects whose delete failed. + */ +const sweepOrphanObjects = (database: DatabaseApi, bucket: WritableObjectStore, now: number) => + Effect.gen(function* () { + const dbExecute = makeDbExecute(database, "SourceMapService", toStorageError) + const storeError = Effect.mapError(toStorageError) + const cursorBytes = yield* bucket.getBytes(ORPHAN_CURSOR_KEY).pipe(storeError) + const cursor = Option.filter( + Option.map(cursorBytes, (bytes) => new TextDecoder().decode(bytes)), + Str.startsWith(OBJECT_PREFIX), + ) + const page = yield* bucket + .list({ prefix: OBJECT_PREFIX, startAfter: Option.getOrUndefined(cursor), limit: ORPHAN_PAGE }) + .pipe(storeError) + const cutoff = now - Duration.toMillis(ORPHAN_MIN_AGE) + // Keys this service did not write (no file id) are left alone. + const candidates = Arr.getSomes( + Arr.map( + Arr.filter(page.objects, (object) => object.uploadedAt < cutoff), + (object) => + Option.map( + Option.flatMap(Arr.last(Str.split(object.key, "/")), decodeFileIdOption), + (id) => ({ key: object.key, id }), + ), + ), + ) + const known = + candidates.length === 0 + ? [] + : yield* dbExecute((db) => + db.run( + PG.from(SourceMapFiles) + .select("objectKey") + .where(($) => [ + PG.inList( + $.id, + Arr.map(candidates, (candidate) => candidate.id), + ), + ]) + .crossTenant(), + ), + ) + const knownKeys = new Set(Arr.map(known, (row) => row.objectKey)) + const orphans = Arr.filter( + Arr.map(candidates, (candidate) => candidate.key), + (key) => !knownKeys.has(key), + ) + if (orphans.length > 0) { + yield* bucket.delete(orphans).pipe(storeError) + yield* Effect.logWarning("Deleted source map objects that no row points at").pipe( + Effect.annotateLogs({ count: orphans.length }), + ) + } + // A full pass done, the next tick starts over from the first key. + const last = Arr.last(page.objects) + yield* ( + page.truncated && Option.isSome(last) + ? bucket.put(ORPHAN_CURSOR_KEY, new TextEncoder().encode(last.value.key), "text/plain") + : bucket.delete([ORPHAN_CURSOR_KEY]) + ).pipe(storeError) + return orphans.length + }) + +export class SourceMapService extends Context.Service()( + "@maple/backend/services/sourcemaps/SourceMapService", + { + make: Effect.gen(function* () { + const database = yield* Database + const bucket = yield* SourceMapBucket + const dbExecute = makeDbExecute(database, "SourceMapService", toStorageError) + const rowExecute = makeDbExecute(database, "SourceMapService", (error) => + postgresSqlState(error) === UNIQUE_VIOLATION + ? new SourceMapRowConflict({ message: error.message }) + : toStorageError(error), + ) + + const upload = Effect.fn("SourceMapService.upload")(function* ( + orgId: OrgId, + input: SourceMapUpload, + ) { + yield* Effect.annotateCurrentSpan({ + orgId, + "maple.source_map.size_bytes": input.bytes.byteLength, + }) + const valid = yield* validateSourceMapUpload(input) + const id = decodeFileId(randomUUID()) + const objectKey = sourceMapObjectKey(orgId, id) + const now = yield* Clock.currentTimeMillis + yield* Effect.annotateCurrentSpan({ + "maple.source_map.id": id, + "maple.source_map.has_debug_id": valid.debugId !== null, + }) + + yield* bucket + .put(objectKey, input.bytes, "application/json") + .pipe(Effect.mapError(toStorageError)) + // A failed row write leaves the object: the error may be a lost commit ack for a row + // that did land. A real orphan goes in the hourly orphan sweep a day later. + const replaced = yield* rowExecute((db) => + db.transaction( + Effect.gen(function* () { + const { debugId, serviceName, version, minifiedPath } = valid + const previous = yield* db.run( + PG.from(SourceMapFiles) + .select() + .where(($) => [ + $.orgId.eq(orgId), + // A debug id is the whole identity of its build; only a map without + // one replaces by release path, and only another map without one. + debugId !== null + ? $.debugId.eq(debugId) + : PG.and( + $.debugId.isNull(), + $.serviceName.eq(serviceName ?? ""), + $.version.eq(version ?? ""), + $.minifiedPath.eq(minifiedPath), + ), + ]), + ) + if (previous.length > 0) { + const previousIds = Arr.map(previous, (row) => row.id) + yield* db.run( + PG.deleteFrom(SourceMapFiles).where(($) => [ + $.orgId.eq(orgId), + PG.inList($.id, previousIds), + ]), + ) + } + const [row] = yield* db.run( + PG.insertInto(SourceMapFiles) + .values({ + id, + orgId, + debugId, + serviceName, + version, + minifiedPath, + sizeBytes: valid.sizeBytes, + hasSourcesContent: valid.hasSourcesContent, + objectKey, + createdAt: now, + lastUsedAt: null, + }) + .returning(), + ) + return { row, previous } + }), + ), + ).pipe( + // A concurrent upload of the same map committed between the read and the insert; + // the second attempt reads and replaces its row. + Effect.retry({ times: 1, while: Schema.is(SourceMapRowConflict) }), + Effect.catchTag("@maple/backend/sourcemaps/SourceMapRowConflict", (error) => + Effect.fail(new SourceMapStorageError({ message: error.message })), + ), + ) + // The replaced objects are unreferenced now; a failed delete only leaves bytes behind. + yield* deleteObjects(bucket, replaced.previous).pipe( + Effect.tapError((error) => + Effect.logWarning("Replaced source map objects were not deleted").pipe( + Effect.annotateLogs({ orgId, message: error.message }), + ), + ), + Effect.ignore, + ) + if (replaced.row === undefined) { + return yield* new SourceMapStorageError({ message: "The source map row was not written" }) + } + return replaced.row + }) + + const list = Effect.fn("SourceMapService.list")(function* ( + orgId: OrgId, + filter: SourceMapListFilter, + ) { + yield* Effect.annotateCurrentSpan({ orgId }) + return yield* dbExecute((db) => + db.run( + PG.from(SourceMapFiles) + .select() + .where(($) => [ + $.orgId.eq(orgId), + filter.serviceName === undefined + ? undefined + : $.serviceName.eq(filter.serviceName), + filter.version === undefined ? undefined : $.version.eq(filter.version), + filter.debugId === undefined + ? undefined + : $.debugId.eq(Str.toLowerCase(filter.debugId)), + ]) + .orderBy(($) => [ + [$.createdAt, "desc"], + [$.id, "desc"], + ]) + .limit(filter.limit) + .offset(filter.offset), + ), + ) + }) + + const remove = Effect.fn("SourceMapService.remove")(function* ( + orgId: OrgId, + id: SourceMapFileId, + ) { + yield* Effect.annotateCurrentSpan({ orgId, "maple.source_map.id": id }) + const [row] = yield* dbExecute((db) => + db.run( + PG.from(SourceMapFiles) + .select() + .where(($) => [$.orgId.eq(orgId), $.id.eq(id)]) + .limit(1), + ), + ) + if (row === undefined) { + return yield* new SourceMapNotFoundError({ + message: "Source map not found", + sourceMapId: id, + }) + } + // Object first: a failed row delete leaves a row a retry can still remove. + yield* deleteObjects(bucket, [row]) + yield* dbExecute((db) => + db.run(PG.deleteFrom(SourceMapFiles).where(($) => [$.orgId.eq(orgId), $.id.eq(id)])), + ) + return row + }) + + const sweepExpired = Effect.fn("SourceMapService.sweepExpired")(function* (now: number) { + const deleted = yield* sweep(database, bucket, now) + yield* Effect.annotateCurrentSpan({ "maple.source_map.swept": deleted }) + return deleted + }) + + const sweepOrphans = Effect.fn("SourceMapService.sweepOrphans")(function* (now: number) { + const deleted = yield* sweepOrphanObjects(database, bucket, now) + yield* Effect.annotateCurrentSpan({ "maple.source_map.orphans_swept": deleted }) + return deleted + }) + + return { + upload, + list, + remove, + sweepExpired, + sweepOrphans, + } satisfies SourceMapServiceApi + }), + }, +) { + static readonly layer = Layer.effect(this, this.make) +} + +/** The hourly retention cron's entry: one sweep at the current time. */ +export const runSourceMapRetention = Effect.gen(function* () { + const database = yield* Database + const bucket = yield* SourceMapBucket + const now = yield* Clock.currentTimeMillis + const deleted = yield* sweep(database, bucket, now) + const orphans = yield* sweepOrphanObjects(database, bucket, now) + yield* Effect.annotateCurrentSpan({ + "maple.source_map.swept": deleted, + "maple.source_map.orphans_swept": orphans, + }) +}).pipe( + Effect.tapCause((cause) => + Effect.logError("[source-maps] retention tick failed").pipe( + Effect.annotateLogs({ error: String(cause) }), + ), + ), + Effect.withSpan("SourceMapRetention.tick"), +) diff --git a/packages/backend/src/services/sourcemaps/StackSymbolicator.test.ts b/packages/backend/src/services/sourcemaps/StackSymbolicator.test.ts new file mode 100644 index 0000000000..2af12d8610 --- /dev/null +++ b/packages/backend/src/services/sourcemaps/StackSymbolicator.test.ts @@ -0,0 +1,743 @@ +import { afterEach, assert, describe, it } from "@effect/vitest" +import { OrgId } from "@maple/domain/http" +import { Array as Arr, Deferred, Duration, Effect, Fiber, Layer, Schema } from "effect" +import { TestClock } from "effect/testing" +import { + inMemoryObjectStore, + ObjectStoreError, + sourceMapBucketLayer, + type WritableObjectStore, +} from "@maple/backend/platform/bindings" +import * as PG from "@maple-dev/effect-orm/postgres" +import { SourceMapFiles, type SourceMapFileRow } from "@maple/db/tables" +import { Database } from "@maple/backend/platform/DatabaseLive" +import { cleanupTestDbs, createTestDb, type TestDb } from "@maple/backend/testing/test-pglite" +import { SourceMapReader } from "./SourceMapReader" +import { SourceMapService } from "./SourceMapService" +import { + PARSED_MAP_SIZE_FACTOR, + type SymbolicateRequest, + StackSymbolicator, + SYMBOLICATION_MAX_MAP_BYTES, +} from "./StackSymbolicator" + +const createdDbs: TestDb[] = [] +afterEach(() => cleanupTestDbs(createdDbs)) + +const ORG = Schema.decodeSync(OrgId)("org_symbolicator") +const DEBUG_ID = "6c5e2b1a-1f2e-4d3c-8b7a-0123456789ab" +const BUNDLE_URL = "https://shop.example.com/assets/index-Bx81.js" +const STACK = `TypeError: boom\n at a (${BUNDLE_URL}:1:1)` + +const APP_SOURCE = Arr.join( + Arr.makeBy(14, (i) => `// app line ${i + 1}`), + "\n", +) + +// One segment: generated 1:0 -> src/app.ts 7:0, named handleClick (`AAMAA` is [0, 0, +6, 0, 0]). +const mapBytes = (mappings = "AAMAA") => + new TextEncoder().encode( + JSON.stringify({ + version: 3, + sources: ["webpack://shop/./src/app.ts"], + sourcesContent: [APP_SOURCE], + names: ["handleClick"], + mappings, + }), + ) + +const RESOLVED_FRAME = { + raw: `at a (${BUNDLE_URL}:1:1)`, + // A lone frame has no caller call site to name it, so it keeps its minified name. + function: "a", + file: "src/app.ts", + line: 7, + column: 1, + in_app: true, + resolved: true, + context: { + pre: Arr.makeBy(5, (i) => `// app line ${i + 2}`), + line: "// app line 7", + post: Arr.makeBy(5, (i) => `// app line ${i + 8}`), + }, +} + +const request = (overrides: Partial = {}): SymbolicateRequest => ({ + orgId: ORG, + stacktrace: STACK, + serviceName: null, + serviceVersion: null, + debugIds: new Map(), + ...overrides, +}) + +interface BucketState { + reads: number + failReads: boolean + /** While set, reads wait for it. */ + gate: Deferred.Deferred | undefined + /** Completed when a read starts (before it waits on the gate). */ + readStarted: Deferred.Deferred | undefined + /** Completed when a frame lookup returns. */ + lookedUp: Deferred.Deferred | undefined + /** Frame lookups made (each is one or more Postgres reads). */ + lookups: number +} + +/** An in-memory bucket that counts reads and can be made to fail or hold them. */ +const makeHarness = () => { + const objects = new Map() + const state: BucketState = { + reads: 0, + failReads: false, + gate: undefined, + readStarted: undefined, + lookedUp: undefined, + lookups: 0, + } + const signal = (deferred: Deferred.Deferred | undefined) => + deferred === undefined ? Effect.void : Deferred.succeed(deferred, undefined) + const memory = inMemoryObjectStore(objects) + const bucket: WritableObjectStore = { + ...memory, + getBytes: (key) => + Effect.suspend(() => { + state.reads += 1 + const read = state.failReads + ? Effect.fail(new ObjectStoreError({ message: "bucket unavailable", cause: undefined })) + : memory.getBytes(key) + const started = signal(state.readStarted) + return state.gate === undefined + ? Effect.andThen(started, read) + : Effect.andThen(started, Effect.andThen(Deferred.await(state.gate), read)) + }), + } + const sourceMaps = Layer.mergeAll( + Layer.effect(SourceMapService, SourceMapService.make), + Layer.effect( + SourceMapReader, + Effect.map(SourceMapReader.make, (reader) => ({ + ...reader, + findForFrames: (lookup: Parameters[0]) => + Effect.tap(reader.findForFrames(lookup), () => + Effect.andThen( + Effect.sync(() => { + state.lookups += 1 + }), + signal(state.lookedUp), + ), + ), + })), + ), + ).pipe(Layer.provideMerge(createTestDb(createdDbs).layer), Layer.provide(sourceMapBucketLayer(bucket))) + const layer = Layer.effect(StackSymbolicator, StackSymbolicator.make).pipe(Layer.provideMerge(sourceMaps)) + return { state, layer, objects } +} + +/** + * Forks `run` twice: the first is let through to its (gated) bucket read, the second only once + * that read is blocked, and is returned once its lookup is done and it is waiting on that load. + */ +const joinedLoad = (state: BucketState, run: Effect.Effect) => + Effect.gen(function* () { + state.readStarted = yield* Deferred.make() + const loading = yield* Effect.forkChild(run) + yield* Deferred.await(state.readStarted) + state.readStarted = undefined + state.lookedUp = yield* Deferred.make() + const waiting = yield* Effect.forkChild(run) + yield* Deferred.await(state.lookedUp) + state.lookedUp = undefined + // From its lookup to waiting on the shared load the fiber does no I/O; let it run there. + yield* Effect.yieldNow + yield* Effect.yieldNow + return [loading, waiting] as const + }) + +describe("StackSymbolicator", () => { + it.effect("resolves a frame through the map its debug id names, whatever the file is called", () => { + const { layer } = makeHarness() + return Effect.gen(function* () { + const sourceMaps = yield* SourceMapService + const symbolicator = yield* StackSymbolicator + yield* sourceMaps.upload(ORG, { + bytes: mapBytes(), + minifiedPath: "assets/renamed-later.js", + debugId: DEBUG_ID, + }) + + const stack = yield* symbolicator.symbolicate( + request({ debugIds: new Map([[BUNDLE_URL, DEBUG_ID]]) }), + ) + assert.deepStrictEqual(stack, { status: "resolved", frames: [RESOLVED_FRAME], missing: [] }) + }).pipe(Effect.provide(layer)) + }) + + it.effect("falls back to service, version and path, and marks the file used", () => { + const { layer } = makeHarness() + return Effect.gen(function* () { + const sourceMaps = yield* SourceMapService + const symbolicator = yield* StackSymbolicator + const release = { serviceName: "shop-web", version: "2.4.0" } + yield* sourceMaps.upload(ORG, { + bytes: mapBytes(), + minifiedPath: "assets/index-Bx81.js", + ...release, + }) + + const otherVersion = yield* symbolicator.symbolicate( + request({ serviceName: "shop-web", serviceVersion: "2.3.0" }), + ) + assert.strictEqual(otherVersion.status, "missing_map") + assert.deepStrictEqual(otherVersion.missing, [BUNDLE_URL]) + + const stack = yield* symbolicator.symbolicate( + request({ serviceName: "shop-web", serviceVersion: "2.4.0" }), + ) + assert.deepStrictEqual(stack.frames, [RESOLVED_FRAME]) + const [row] = yield* sourceMaps.list(ORG, { limit: 1, offset: 0 }) + assert.isNotNull(row?.lastUsedAt ?? null) + }).pipe(Effect.provide(layer)) + }) + + it.effect("parses a map once and serves later stacks from the cache", () => { + const { state, layer } = makeHarness() + return Effect.gen(function* () { + const sourceMaps = yield* SourceMapService + const symbolicator = yield* StackSymbolicator + yield* sourceMaps.upload(ORG, { + bytes: mapBytes(), + minifiedPath: "assets/index-Bx81.js", + debugId: DEBUG_ID, + }) + const withDebugId = request({ debugIds: new Map([[BUNDLE_URL, DEBUG_ID]]) }) + + const first = yield* symbolicator.symbolicate(withDebugId) + const second = yield* symbolicator.symbolicate(withDebugId) + assert.strictEqual(state.reads, 1) + assert.deepStrictEqual(second, first) + assert.strictEqual(second.status, "resolved") + }).pipe(Effect.provide(layer)) + }) + + it.effect("remembers a URL with no map for five minutes, then finds a late upload", () => { + const { layer } = makeHarness() + return Effect.gen(function* () { + const sourceMaps = yield* SourceMapService + const symbolicator = yield* StackSymbolicator + const release = request({ serviceName: "shop-web", serviceVersion: "2.4.0" }) + // The org has a map, so the miss comes from the URL lookup, not the org's no-maps answer. + yield* sourceMaps.upload(ORG, { + bytes: mapBytes(), + minifiedPath: "assets/unrelated.js", + debugId: DEBUG_ID, + }) + + assert.strictEqual((yield* symbolicator.symbolicate(release)).status, "missing_map") + yield* sourceMaps.upload(ORG, { + bytes: mapBytes(), + minifiedPath: "assets/index-Bx81.js", + serviceName: "shop-web", + version: "2.4.0", + }) + assert.strictEqual((yield* symbolicator.symbolicate(release)).status, "missing_map") + // Past the one-minute org cache, the URL is still remembered as missing. + yield* TestClock.adjust(Duration.minutes(2)) + assert.strictEqual((yield* symbolicator.symbolicate(release)).status, "missing_map") + + yield* TestClock.adjust(Duration.minutes(3)) + assert.strictEqual((yield* symbolicator.symbolicate(release)).status, "resolved") + }).pipe(Effect.provide(layer)) + }) + + it.effect("leaves frames unresolved when the bucket fails, and tries again next time", () => { + const { state, layer } = makeHarness() + return Effect.gen(function* () { + const sourceMaps = yield* SourceMapService + const symbolicator = yield* StackSymbolicator + yield* sourceMaps.upload(ORG, { + bytes: mapBytes(), + minifiedPath: "assets/index-Bx81.js", + debugId: DEBUG_ID, + }) + const withDebugId = request({ debugIds: new Map([[BUNDLE_URL, DEBUG_ID]]) }) + + state.failReads = true + const failed = yield* symbolicator.symbolicate(withDebugId) + assert.strictEqual(failed.status, "missing_map") + assert.deepStrictEqual( + Arr.map(failed.frames, (frame) => [frame.file, frame.line, frame.resolved]), + [[BUNDLE_URL, 1, false]], + ) + + state.failReads = false + assert.strictEqual((yield* symbolicator.symbolicate(withDebugId)).status, "resolved") + }).pipe(Effect.provide(layer)) + }) + + it.effect("answers a stack with no JavaScript files without looking anything up", () => { + const unreachable = Layer.succeed(SourceMapReader, { + hasAny: () => Effect.die("hasAny"), + findForFrames: () => Effect.die("findForFrames"), + load: () => Effect.die("load"), + touch: () => Effect.die("touch"), + }) + return Effect.gen(function* () { + const symbolicator = yield* StackSymbolicator + const python = yield* symbolicator.symbolicate( + request({ + stacktrace: 'Traceback (most recent call last):\n File "app.py", line 3, in ', + }), + ) + assert.deepStrictEqual(python, { status: "not_applicable", frames: [], missing: [] }) + const java = yield* symbolicator.symbolicate( + request({ + stacktrace: "java.lang.IllegalStateException\n\tat com.shop.Cart.add(Cart.java:42)", + }), + ) + assert.strictEqual(java.status, "not_applicable") + assert.deepStrictEqual(java.missing, []) + }).pipe( + Effect.provide( + Layer.effect(StackSymbolicator, StackSymbolicator.make).pipe(Layer.provide(unreachable)), + ), + ) + }) + it.effect("skips a map over the symbolication limit, leaving its frames unresolved", () => { + const { state, layer } = makeHarness() + return Effect.gen(function* () { + const sourceMaps = yield* SourceMapService + const symbolicator = yield* StackSymbolicator + const row = yield* sourceMaps.upload(ORG, { + bytes: mapBytes(), + minifiedPath: "assets/index-Bx81.js", + debugId: DEBUG_ID, + }) + // Records the file as over the limit without building one that large. + const database = yield* Database + yield* database.execute((db) => + db.run( + PG.update(SourceMapFiles) + .set({ sizeBytes: SYMBOLICATION_MAX_MAP_BYTES + 1 }) + .where(($) => [$.id.eq(row.id)]), + ), + ) + + const stack = yield* symbolicator.symbolicate( + request({ debugIds: new Map([[BUNDLE_URL, DEBUG_ID]]) }), + ) + assert.strictEqual(stack.status, "missing_map") + assert.strictEqual(state.reads, 0) + }).pipe(Effect.provide(layer)) + }) + + it.effect("looks nothing up for an org with no maps, and notices its first upload", () => { + const { state, layer } = makeHarness() + return Effect.gen(function* () { + const sourceMaps = yield* SourceMapService + const symbolicator = yield* StackSymbolicator + const withDebugId = request({ debugIds: new Map([[BUNDLE_URL, DEBUG_ID]]) }) + + assert.isFalse(yield* symbolicator.hasSourceMaps(ORG)) + const none = yield* symbolicator.symbolicate(withDebugId) + assert.strictEqual(none.status, "missing_map") + assert.deepStrictEqual(none.missing, [BUNDLE_URL]) + + yield* sourceMaps.upload(ORG, { + bytes: mapBytes(), + minifiedPath: "assets/index-Bx81.js", + debugId: DEBUG_ID, + }) + yield* TestClock.adjust(Duration.minutes(1)) + assert.isTrue(yield* symbolicator.hasSourceMaps(ORG)) + assert.strictEqual((yield* symbolicator.symbolicate(withDebugId)).status, "resolved") + assert.strictEqual(state.reads, 1) + }).pipe(Effect.provide(layer)) + }) + it.live("shares one load between concurrent stacks and counts a cached map once", () => { + const { state, layer } = makeHarness() + const OTHER_ID = "7d6f3c2b-2a3f-4e4d-9c8b-1234567890ab" + const OTHER_URL = "https://shop.example.com/assets/chunk-Zz91.js" + return Effect.gen(function* () { + const sourceMaps = yield* SourceMapService + const symbolicator = yield* StackSymbolicator + const database = yield* Database + const first = yield* sourceMaps.upload(ORG, { + bytes: mapBytes(), + minifiedPath: "assets/index-Bx81.js", + debugId: DEBUG_ID, + }) + const second = yield* sourceMaps.upload(ORG, { + bytes: mapBytes(), + minifiedPath: "assets/chunk-Zz91.js", + debugId: OTHER_ID, + }) + // Each parsed map is estimated at just under half the cache, so both fit only when + // every map is counted once. + const nearHalf = Math.floor((40 * 1024 * 1024) / 2 / PARSED_MAP_SIZE_FACTOR) - 1024 + yield* database.execute((db) => + db.run( + PG.update(SourceMapFiles) + .set({ sizeBytes: nearHalf }) + .where(($) => [PG.inList($.id, [first.id, second.id])]), + ), + ) + const withDebugId = request({ debugIds: new Map([[BUNDLE_URL, DEBUG_ID]]) }) + + const gate = yield* Deferred.make() + state.gate = gate + const fibers = yield* joinedLoad(state, symbolicator.symbolicate(withDebugId)) + yield* Deferred.succeed(gate, undefined) + state.gate = undefined + const stacks = yield* Fiber.joinAll(fibers) + assert.deepStrictEqual( + Arr.map(stacks, (stack) => stack.status), + ["resolved", "resolved"], + ) + assert.strictEqual(state.reads, 1) + + const other = yield* symbolicator.symbolicate( + request({ + stacktrace: `TypeError: boom\n at a (${OTHER_URL}:1:1)`, + debugIds: new Map([[OTHER_URL, OTHER_ID]]), + }), + ) + assert.strictEqual(other.status, "resolved") + assert.strictEqual((yield* symbolicator.symbolicate(withDebugId)).status, "resolved") + assert.strictEqual(state.reads, 2) + }).pipe(Effect.provide(layer)) + }) + + it.live("leaves stacks waiting on an interrupted load unresolved, and loads again later", () => { + const { state, layer } = makeHarness() + return Effect.gen(function* () { + const sourceMaps = yield* SourceMapService + const symbolicator = yield* StackSymbolicator + yield* sourceMaps.upload(ORG, { + bytes: mapBytes(), + minifiedPath: "assets/index-Bx81.js", + debugId: DEBUG_ID, + }) + const withDebugId = request({ debugIds: new Map([[BUNDLE_URL, DEBUG_ID]]) }) + + state.gate = yield* Deferred.make() + const [loading, waiting] = yield* joinedLoad( + state, + symbolicator.symbolicateWithOutcome(withDebugId), + ) + if (loading === undefined || waiting === undefined) return assert.fail("both fibers start") + yield* Fiber.interrupt(loading) + const waited = yield* Fiber.join(waiting) + assert.deepStrictEqual([waited.stack.status, waited.lookupFailed], ["missing_map", true]) + + state.gate = undefined + assert.strictEqual((yield* symbolicator.symbolicate(withDebugId)).status, "resolved") + }).pipe(Effect.provide(layer)) + }) + + it.effect("says when a map read failed", () => { + const { state, layer } = makeHarness() + return Effect.gen(function* () { + const sourceMaps = yield* SourceMapService + const symbolicator = yield* StackSymbolicator + yield* sourceMaps.upload(ORG, { + bytes: mapBytes(), + minifiedPath: "assets/index-Bx81.js", + debugId: DEBUG_ID, + }) + const withDebugId = request({ debugIds: new Map([[BUNDLE_URL, DEBUG_ID]]) }) + state.failReads = true + const failed = yield* symbolicator.symbolicateWithOutcome(withDebugId) + assert.isTrue(failed.lookupFailed) + state.failReads = false + const ok = yield* symbolicator.symbolicateWithOutcome(withDebugId) + assert.deepStrictEqual([ok.lookupFailed, ok.stack.status], [false, "resolved"]) + }).pipe(Effect.provide(layer)) + }) + + it.effect("keeps two builds with their own debug ids on one release path apart", () => { + const { layer } = makeHarness() + return Effect.gen(function* () { + const sourceMaps = yield* SourceMapService + const symbolicator = yield* StackSymbolicator + const OTHER_DEBUG_ID = "7d6f3c2b-2a3f-4e4d-9c8b-123456789abc" + const release = { + serviceName: "shop-web", + version: "2.4.0", + minifiedPath: "assets/index-Bx81.js", + } + yield* sourceMaps.upload(ORG, { bytes: mapBytes(), debugId: DEBUG_ID, ...release }) + // The second build maps the same position to line 11 (`AAUAA` is [0, 0, +10, 0, 0]). + yield* sourceMaps.upload(ORG, { bytes: mapBytes("AAUAA"), debugId: OTHER_DEBUG_ID, ...release }) + assert.strictEqual((yield* sourceMaps.list(ORG, { limit: 10, offset: 0 })).length, 2) + + const lineFor = (debugId: string) => + Effect.map( + symbolicator.symbolicate( + request({ + serviceName: "shop-web", + serviceVersion: "2.4.0", + debugIds: new Map([[BUNDLE_URL, debugId]]), + }), + ), + (stack) => stack.frames[0]?.line, + ) + assert.strictEqual(yield* lineFor(DEBUG_ID), 7) + assert.strictEqual(yield* lineFor(OTHER_DEBUG_ID), 11) + }).pipe(Effect.provide(layer)) + }) + + it.effect("records use only for a map that resolved a frame", () => { + const { layer } = makeHarness() + return Effect.gen(function* () { + const sourceMaps = yield* SourceMapService + const symbolicator = yield* StackSymbolicator + yield* sourceMaps.upload(ORG, { + bytes: mapBytes(), + minifiedPath: "assets/index-Bx81.js", + debugId: DEBUG_ID, + }) + // Line 5 has no mapping: the map loads but resolves nothing. + const unmapped = yield* symbolicator.symbolicate( + request({ + stacktrace: `TypeError: boom\n at a (${BUNDLE_URL}:5:1)`, + debugIds: new Map([[BUNDLE_URL, DEBUG_ID]]), + }), + ) + assert.strictEqual(unmapped.status, "missing_map") + const [untouched] = yield* sourceMaps.list(ORG, { limit: 1, offset: 0 }) + assert.isNull(untouched?.lastUsedAt ?? null) + + yield* symbolicator.symbolicate(request({ debugIds: new Map([[BUNDLE_URL, DEBUG_ID]]) })) + const [touched] = yield* sourceMaps.list(ORG, { limit: 1, offset: 0 }) + assert.isNotNull(touched?.lastUsedAt ?? null) + }).pipe(Effect.provide(layer)) + }) + + it.effect("loads no more maps for one stack than its memory budget", () => { + const { state, layer } = makeHarness() + const OTHER_ID = "7d6f3c2b-2a3f-4e4d-9c8b-1234567890ab" + const OTHER_URL = "https://shop.example.com/assets/chunk-Zz91.js" + return Effect.gen(function* () { + const sourceMaps = yield* SourceMapService + const symbolicator = yield* StackSymbolicator + const database = yield* Database + const rows = yield* Effect.forEach( + [ + ["assets/index-Bx81.js", DEBUG_ID], + ["assets/chunk-Zz91.js", OTHER_ID], + ] as const, + ([minifiedPath, debugId]) => + sourceMaps.upload(ORG, { bytes: mapBytes(), minifiedPath, debugId }), + ) + // Each estimated at 36 MiB: one fits the 64 MiB budget, two do not. + yield* database.execute((db) => + db.run( + PG.update(SourceMapFiles) + .set({ sizeBytes: 6 * 1024 * 1024 }) + .where(($) => [ + PG.inList( + $.id, + Arr.map(rows, (row) => row.id), + ), + ]), + ), + ) + const stack = yield* symbolicator.symbolicate( + request({ + stacktrace: `TypeError: boom\n at a (${BUNDLE_URL}:1:1)\n at b (${OTHER_URL}:1:1)`, + debugIds: new Map([ + [BUNDLE_URL, DEBUG_ID], + [OTHER_URL, OTHER_ID], + ]), + }), + ) + assert.deepStrictEqual( + Arr.map(stack.frames, (frame) => frame.resolved), + [true, false], + ) + assert.strictEqual(state.reads, 1) + }).pipe(Effect.provide(layer)) + }) + + it.effect("counts a matched map whose object is gone as a failed read", () => { + const { objects, layer } = makeHarness() + return Effect.gen(function* () { + const sourceMaps = yield* SourceMapService + const symbolicator = yield* StackSymbolicator + const row = yield* sourceMaps.upload(ORG, { + bytes: mapBytes(), + minifiedPath: "assets/index-Bx81.js", + debugId: DEBUG_ID, + }) + // Replaced or deleted between the lookup and the read: the row is there, its bytes are not. + objects.delete(row.objectKey) + const outcome = yield* symbolicator.symbolicateWithOutcome( + request({ debugIds: new Map([[BUNDLE_URL, DEBUG_ID]]) }), + ) + assert.deepStrictEqual([outcome.stack.status, outcome.lookupFailed], ["missing_map", true]) + }).pipe(Effect.provide(layer)) + }) + + it.effect("looks up a URL with no JS extension when the SDK recorded its debug id", () => { + const { layer } = makeHarness() + const BLOB_URL = "blob:https://shop.example.com/0f3a9c1e-6b2d-4e8f-9a7c-1d2e3f4a5b6c" + return Effect.gen(function* () { + const sourceMaps = yield* SourceMapService + const symbolicator = yield* StackSymbolicator + yield* sourceMaps.upload(ORG, { bytes: mapBytes(), minifiedPath: "worker.js", debugId: DEBUG_ID }) + const stacktrace = `TypeError: boom\n at a (${BLOB_URL}:1:1)` + const withId = yield* symbolicator.symbolicate( + request({ stacktrace, debugIds: new Map([[BLOB_URL, DEBUG_ID]]) }), + ) + assert.deepStrictEqual( + Arr.map(withId.frames, (frame) => [frame.file, frame.line]), + [["src/app.ts", 7]], + ) + const without = yield* symbolicator.symbolicate(request({ stacktrace })) + assert.isFalse(without.frames[0]?.resolved ?? true) + }).pipe(Effect.provide(layer)) + }) + + it.effect("looks a bundle up once for a whole batch of its stacks", () => { + const { state, layer } = makeHarness() + return Effect.gen(function* () { + const sourceMaps = yield* SourceMapService + const symbolicator = yield* StackSymbolicator + yield* sourceMaps.upload(ORG, { + bytes: mapBytes(), + minifiedPath: "assets/index-Bx81.js", + serviceName: "shop-web", + version: "2.4.0", + }) + const lookupMemo = new Map() + const stacks = yield* Effect.forEach( + Arr.makeBy(200, () => + request({ serviceName: "shop-web", serviceVersion: "2.4.0", lookupMemo }), + ), + (req) => symbolicator.symbolicate(req), + { concurrency: 4 }, + ) + assert.isTrue(Arr.every(stacks, (stack) => stack.status === "resolved")) + assert.isAtMost(state.lookups, 4) + assert.strictEqual(state.reads, 1) + }).pipe(Effect.provide(layer)) + }) + + it.effect("looks again when a batch's remembered map was replaced since", () => { + const { objects, state, layer } = makeHarness() + return Effect.gen(function* () { + const sourceMaps = yield* SourceMapService + const symbolicator = yield* StackSymbolicator + const release = { + serviceName: "shop-web", + version: "2.4.0", + minifiedPath: "assets/index-Bx81.js", + } + const first = yield* sourceMaps.upload(ORG, { bytes: mapBytes(), ...release }) + const lookupMemo = new Map() + const req = request({ serviceName: "shop-web", serviceVersion: "2.4.0", lookupMemo }) + const withFirst = yield* symbolicator.symbolicateWithOutcome(req) + assert.strictEqual(withFirst.stack.frames[0]?.line, 7) + // Replaced, and the old map dropped from this isolate's parsed cache by a bigger one. + yield* sourceMaps.upload(ORG, { bytes: mapBytes("AAUAA"), ...release }) + assert.isFalse(objects.has(first.objectKey)) + const replacedAndEvicted = Arr.makeBy(9, (i) => `assets/filler-${i}.js`) + yield* Effect.forEach(replacedAndEvicted, (minifiedPath, i) => + Effect.andThen( + sourceMaps.upload(ORG, { + bytes: mapBytes(), + minifiedPath, + debugId: `00000000-0000-4000-8000-00000000000${i}`, + }), + (row) => + symbolicator.symbolicate( + request({ + stacktrace: `TypeError: boom\n at a (https://shop.example.com/${minifiedPath}:1:1)`, + debugIds: new Map([ + [`https://shop.example.com/${minifiedPath}`, row.debugId ?? ""], + ]), + }), + ), + ), + ) + const stale = yield* symbolicator.symbolicateWithOutcome(req) + assert.deepStrictEqual([stale.stack.status, stale.lookupFailed], ["missing_map", true]) + const lookupsBefore = state.lookups + const fresh = yield* symbolicator.symbolicateWithOutcome(req) + assert.strictEqual(fresh.stack.frames[0]?.line, 11) + assert.strictEqual(state.lookups, lookupsBefore + 1) + }).pipe(Effect.provide(layer)) + }) + + it.effect("parses a map over the cache budget once, keeping it as the only entry", () => { + const { state, layer } = makeHarness() + return Effect.gen(function* () { + const sourceMaps = yield* SourceMapService + const symbolicator = yield* StackSymbolicator + const database = yield* Database + const row = yield* sourceMaps.upload(ORG, { + bytes: mapBytes(), + minifiedPath: "assets/index-Bx81.js", + debugId: DEBUG_ID, + }) + // 7 MiB estimates to 42 MiB, over the 40 MiB cache budget. + yield* database.execute((db) => + db.run( + PG.update(SourceMapFiles) + .set({ sizeBytes: 7 * 1024 * 1024 }) + .where(($) => [PG.inList($.id, [row.id])]), + ), + ) + const withDebugId = request({ debugIds: new Map([[BUNDLE_URL, DEBUG_ID]]) }) + yield* symbolicator.symbolicate(withDebugId) + yield* symbolicator.symbolicate(withDebugId) + assert.strictEqual(state.reads, 1) + }).pipe(Effect.provide(layer)) + }) + + it.effect("leaves a map over the budget unloaded without crowding out a later small one", () => { + const { state, layer } = makeHarness() + const urls = Arr.makeBy(3, (i) => `https://shop.example.com/assets/part-${i}.js`) + const ids = Arr.makeBy(3, (i) => `7d6f3c2b-2a3f-4e4d-9c8b-12345678900${i}`) + return Effect.gen(function* () { + const sourceMaps = yield* SourceMapService + const symbolicator = yield* StackSymbolicator + const database = yield* Database + const rows = yield* Effect.forEach(urls, (url, i) => + sourceMaps.upload(ORG, { + bytes: mapBytes(), + minifiedPath: `assets/part-${i}.js`, + debugId: ids[i] ?? "", + }), + ) + // 2, 9 and 2 MiB: 12, 54 and 12 MiB by estimate against the 64 MiB budget. + yield* Effect.forEach( + Arr.zip(rows, [2, 9, 2]), + ([row, mib]) => + database.execute((db) => + db.run( + PG.update(SourceMapFiles) + .set({ sizeBytes: mib * 1024 * 1024 }) + .where(($) => [PG.inList($.id, [row.id])]), + ), + ), + { discard: true }, + ) + const stack = yield* symbolicator.symbolicate( + request({ + stacktrace: Arr.join( + ["TypeError: boom", ...Arr.map(urls, (url) => ` at a (${url}:1:1)`)], + "\n", + ), + debugIds: new Map(Arr.zip(urls, ids)), + }), + ) + assert.deepStrictEqual( + Arr.map(stack.frames, (frame) => frame.resolved), + [true, false, true], + ) + assert.strictEqual(state.reads, 2) + }).pipe(Effect.provide(layer)) + }) +}) diff --git a/packages/backend/src/services/sourcemaps/StackSymbolicator.ts b/packages/backend/src/services/sourcemaps/StackSymbolicator.ts new file mode 100644 index 0000000000..5609ec26ae --- /dev/null +++ b/packages/backend/src/services/sourcemaps/StackSymbolicator.ts @@ -0,0 +1,501 @@ +import { TraceMap } from "@jridgewell/trace-mapping" +import type { SourceMapFileRow } from "@maple/db/tables" +import { SOURCE_MAP_MAX_BYTES } from "@maple/domain/http" +import { parseJsStack, type SymbolicatedStack } from "@maple/domain/errors/js-stack" +import type { OrgId, SourceMapFileId } from "@maple/primitives" +import { Array as Arr, Clock, Context, Deferred, Duration, Effect, Exit, Layer, Option } from "effect" +import { isLookupUrl } from "./source-map-files" +import { SourceMapReader } from "./SourceMapReader" +import { symbolicateStack } from "./symbolicate" + +/** + * Larger maps are not loaded: parsing one costs several times its size in a 128 MB isolate. Uploads + * are capped at the same size; this only guards maps stored before the cap. + */ +export const SYMBOLICATION_MAX_MAP_BYTES = SOURCE_MAP_MAX_BYTES +/** A parsed map's heap, estimated from its file size (decoded mappings plus the parsed JSON). */ +export const PARSED_MAP_SIZE_FACTOR = 6 +/** Parsed maps kept per isolate: at most this many, and this much estimated heap. */ +const MAP_CACHE_MAX_ENTRIES = 8 +const MAP_CACHE_MAX_ESTIMATED_BYTES = 40 * 1024 * 1024 +/** How long a frame URL with no stored map is not looked up again; short, so a late upload shows soon. */ +const NEGATIVE_TTL = Duration.minutes(5) +const NEGATIVE_MAX_ENTRIES = 10_000 +/** `last_used_at` is asked for at most this often per file from one isolate. */ +const TOUCH_INTERVAL = Duration.hours(1) +const TOUCHED_MAX_ENTRIES = 10_000 +/** + * Estimated heap of the parsed maps one request holds at once. The first map always loads (one map + * at the upload cap is 60 MiB by estimate); later ones load only while the total stays under this. + */ +export const REQUEST_MAX_ESTIMATED_BYTES = 64 * 1024 * 1024 +/** How long one isolate trusts its answer to "does this org have any maps"; short, so a first upload shows soon. */ +const HAS_MAPS_TTL = Duration.minutes(1) +const HAS_MAPS_MAX_ENTRIES = 10_000 + +export interface SymbolicateRequest { + readonly orgId: OrgId + readonly stacktrace: string + readonly serviceName: string | null + readonly serviceVersion: string | null + /** Frame URL to debug id, from the exception event's `maple.exception.debug_ids`. */ + readonly debugIds: ReadonlyMap + /** + * Shared by the stacks of one batch (an errors tick): a URL's match is looked up once for all of + * them. Absent, every stack looks up its own. + */ + readonly lookupMemo?: Map +} + +export interface SymbolicationOutcome { + readonly stack: SymbolicatedStack + /** A source map lookup or a map read failed; frames it would have mapped stay unresolved. */ + readonly lookupFailed: boolean +} + +interface LoadedMap { + readonly map: Option.Option + readonly cacheHit: boolean + /** The bucket read failed or the object was gone (an unparseable map is not a failure). */ + readonly failed: boolean +} + +/** What waiters on a load that was interrupted get: no map, counted as a failed read. */ +const UNREAD_MAP: LoadedMap = { map: Option.none(), cacheHit: false, failed: true } + +export interface StackSymbolicatorApi { + /** Maps a stack through the org's source maps. Never fails: a frame whose map cannot be read stays unresolved. */ + readonly symbolicate: (request: SymbolicateRequest) => Effect.Effect + /** The same, saying whether a lookup or a map read failed (so a missing frame may yet map). */ + readonly symbolicateWithOutcome: (request: SymbolicateRequest) => Effect.Effect + /** Whether the org has stored any source map, cached briefly per isolate; true when unknown. */ + readonly hasSourceMaps: (orgId: OrgId) => Effect.Effect + /** The same, `None` when the lookup failed, for callers that must not guess. */ + readonly sourceMapsKnown: (orgId: OrgId) => Effect.Effect> +} + +interface CachedMap { + readonly map: TraceMap + /** Estimated heap of the parsed map. */ + readonly bytes: number +} + +const parseTraceMap = Option.liftThrowable((json: string) => new TraceMap(json)) + +/** The stack with every frame unresolved, for when nothing could be looked up. */ +const unresolvedStack = (stacktrace: string, debugIds?: ReadonlyMap): SymbolicatedStack => + symbolicateStack(stacktrace, () => undefined, debugIds) + +const notApplicable = (stacktrace: string): SymbolicatedStack => ({ + ...unresolvedStack(stacktrace), + status: "not_applicable", + missing: [], +}) + +export class StackSymbolicator extends Context.Service()( + "@maple/backend/services/sourcemaps/StackSymbolicator", + { + make: Effect.gen(function* () { + const sourceMaps = yield* SourceMapReader + // Insertion order is recency: a hit is re-inserted, eviction takes the oldest. + const maps = new Map() + let cachedBytes = 0 + const noMapUntil = new Map() + const touchedAt = new Map() + const inflight = new Map>() + const hasMapsAt = new Map() + + const sourceMapsKnown = Effect.fn("StackSymbolicator.sourceMapsKnown")(function* (orgId: OrgId) { + const now = yield* Clock.currentTimeMillis + const cached = hasMapsAt.get(orgId) + if (cached !== undefined && cached.until > now) return Option.some(cached.value) + const value = yield* sourceMaps.hasAny(orgId).pipe( + Effect.tapError((error) => + Effect.logWarning("Whether the org has source maps could not be read").pipe( + Effect.annotateLogs({ orgId, message: error.message }), + ), + ), + Effect.option, + ) + if (Option.isNone(value)) return Option.none() + hasMapsAt.delete(orgId) + hasMapsAt.set(orgId, { value: value.value, until: now + Duration.toMillis(HAS_MAPS_TTL) }) + if (hasMapsAt.size > HAS_MAPS_MAX_ENTRIES) { + Arr.forEach( + Arr.take(Array.from(hasMapsAt.keys()), hasMapsAt.size - HAS_MAPS_MAX_ENTRIES), + (key) => hasMapsAt.delete(key), + ) + } + return Option.some(value.value) + }) + + // Unknown counts as yes: a failed check must not hide maps the lookup can still find. + const hasSourceMaps = (orgId: OrgId) => + Effect.map( + sourceMapsKnown(orgId), + Option.getOrElse(() => true), + ) + + const cacheGet = (id: SourceMapFileId): CachedMap | undefined => { + const hit = maps.get(id) + if (hit !== undefined) { + maps.delete(id) + maps.set(id, hit) + } + return hit + } + + const cachePut = (id: SourceMapFileId, entry: CachedMap) => { + // A map over the budget is kept only alone, so it parses once per isolate, not per stack; + // the next map put evicts it, oldest first. + if (entry.bytes > MAP_CACHE_MAX_ESTIMATED_BYTES) { + maps.clear() + maps.set(id, entry) + cachedBytes = entry.bytes + return + } + const previous = maps.get(id) + if (previous !== undefined) { + maps.delete(id) + cachedBytes -= previous.bytes + } + maps.set(id, entry) + cachedBytes += entry.bytes + Arr.forEach(Array.from(maps.keys()), (key) => { + if (cachedBytes <= MAP_CACHE_MAX_ESTIMATED_BYTES && maps.size <= MAP_CACHE_MAX_ENTRIES) + return + const evicted = maps.get(key) + maps.delete(key) + cachedBytes -= evicted?.bytes ?? 0 + }) + } + + const negativeKey = (request: SymbolicateRequest, url: string) => + Arr.join( + [ + request.orgId, + request.debugIds.get(url) ?? "", + request.serviceName ?? "", + request.serviceVersion ?? "", + url, + ], + "\u0000", + ) + + const markNoMap = (keys: ReadonlyArray, now: number) => { + const until = now + Duration.toMillis(NEGATIVE_TTL) + Arr.forEach(keys, (key) => { + noMapUntil.delete(key) + noMapUntil.set(key, until) + }) + const excess = noMapUntil.size - NEGATIVE_MAX_ENTRIES + if (excess > 0) { + Arr.forEach(Arr.take(Array.from(noMapUntil.keys()), excess), (key) => + noMapUntil.delete(key), + ) + } + } + + const knownMissing = (key: string, now: number): boolean => { + const until = noMapUntil.get(key) + if (until === undefined) return false + if (until > now) return true + noMapUntil.delete(key) + return false + } + + /** Reads and parses one stored file; `None` when it is gone or unreadable. */ + const loadMap = (row: SourceMapFileRow): Effect.Effect => + Effect.gen(function* () { + const json = yield* sourceMaps.load(row).pipe( + Effect.tapError((error) => + Effect.logWarning("Source map could not be loaded").pipe( + Effect.annotateLogs({ + orgId: row.orgId, + sourceMapId: row.id, + message: error.message, + }), + ), + ), + Effect.option, + ) + if (Option.isNone(json)) return { map: Option.none(), cacheHit: false, failed: true } + // A matched row whose object is gone was replaced or deleted mid-request: as unknown + // as a failed read, so a key is not recomputed from the stack's other frames. + if (Option.isNone(json.value)) + return { map: Option.none(), cacheHit: false, failed: true } + const parsed = Option.flatMap(json.value, parseTraceMap) + if (Option.isSome(json.value) && Option.isNone(parsed)) { + yield* Effect.logWarning("Source map could not be parsed").pipe( + Effect.annotateLogs({ orgId: row.orgId, sourceMapId: row.id }), + ) + } + if (Option.isSome(parsed)) + cachePut(row.id, { + map: parsed.value, + bytes: row.sizeBytes * PARSED_MAP_SIZE_FACTOR, + }) + return { map: parsed, cacheHit: false, failed: false } + }) + + /** The parsed map of one stored file; concurrent calls for one file share a single load. */ + const mapOf = (row: SourceMapFileRow): Effect.Effect => + // Uninterruptible from the check to the finalizer: an interrupt in between would leave + // a Deferred no one completes. The load itself stays interruptible. + Effect.uninterruptibleMask((restore) => { + const hit = cacheGet(row.id) + if (hit !== undefined) { + return Effect.succeed({ map: Option.some(hit.map), cacheHit: true, failed: false }) + } + const running = inflight.get(row.id) + if (running !== undefined) { + return Effect.map(restore(Deferred.await(running)), (loaded) => ({ + ...loaded, + cacheHit: true, + })) + } + const deferred = Deferred.makeUnsafe() + inflight.set(row.id, deferred) + return restore(loadMap(row)).pipe( + Effect.onExit((exit) => + Effect.andThen( + Effect.sync(() => inflight.delete(row.id)), + // An interrupted load leaves its waiters unresolved, never failed. + Deferred.succeed(deferred, Exit.isSuccess(exit) ? exit.value : UNREAD_MAP), + ), + ), + ) + }) + + const touchUsed = (orgId: OrgId, ids: ReadonlyArray, now: number) => { + const due = Arr.filter( + ids, + (id) => + now - (touchedAt.get(id) ?? Number.NEGATIVE_INFINITY) >= + Duration.toMillis(TOUCH_INTERVAL), + ) + if (due.length === 0) return Effect.void + return sourceMaps.touch(orgId, due).pipe( + Effect.tap(() => + Effect.sync(() => { + Arr.forEach(due, (id) => { + touchedAt.delete(id) + touchedAt.set(id, now) + }) + // Oldest first: a forgotten file costs one more conditional update, nothing else. + const excess = touchedAt.size - TOUCHED_MAX_ENTRIES + if (excess > 0) { + Arr.forEach(Arr.take(Array.from(touchedAt.keys()), excess), (id) => + touchedAt.delete(id), + ) + } + }), + ), + Effect.catch((error) => + Effect.logWarning("Source map use was not recorded").pipe( + Effect.annotateLogs({ orgId, message: error.message }), + ), + ), + ) + } + + const symbolicateWithOutcome = Effect.fn("StackSymbolicator.symbolicate")(function* ( + request: SymbolicateRequest, + ) { + const { orgId, stacktrace } = request + const parsed = parseJsStack(stacktrace) + const urls = Arr.dedupe( + Arr.filter( + Arr.getSomes(Arr.map(parsed.frames, (frame) => Option.fromNullishOr(frame.url))), + (url) => isLookupUrl(url, request.debugIds), + ), + ) + yield* Effect.annotateCurrentSpan({ + orgId, + "maple.stack.frames": parsed.frames.length, + "maple.stack.js_urls": urls.length, + }) + if (urls.length === 0) { + yield* Effect.annotateCurrentSpan({ "maple.stack.status": "not_applicable" }) + return { + stack: notApplicable(stacktrace), + lookupFailed: false, + } satisfies SymbolicationOutcome + } + + if (!(yield* hasSourceMaps(orgId))) { + const result = unresolvedStack(stacktrace, request.debugIds) + yield* Effect.annotateCurrentSpan({ + "maple.stack.status": result.status, + "maple.stack.org_has_maps": false, + }) + return { stack: result, lookupFailed: false } satisfies SymbolicationOutcome + } + + const now = yield* Clock.currentTimeMillis + // Matches an earlier stack of the same batch found; never kept past the batch, so a map + // replaced since is looked up afresh by the next one. + const memo = request.lookupMemo + const remembered = new Map( + Arr.flatMap(urls, (url) => { + const row = memo?.get(negativeKey(request, url)) + return row === undefined ? [] : [[url, row] as const] + }), + ) + const pending = Arr.filter( + urls, + (url) => !remembered.has(url) && !knownMissing(negativeKey(request, url), now), + ) + const found = + pending.length === 0 + ? Option.some(new Map()) + : yield* sourceMaps + .findForFrames({ + orgId, + debugIds: request.debugIds, + serviceName: request.serviceName, + version: request.serviceVersion, + urls: pending, + }) + .pipe( + Effect.map((rows): ReadonlyMap => rows), + Effect.tapError((error) => + Effect.all([ + Effect.logWarning("Source maps could not be looked up").pipe( + Effect.annotateLogs({ orgId, message: error.message }), + ), + Effect.annotateCurrentSpan({ "maple.stack.lookup_failed": true }), + ]), + ), + Effect.option, + ) + const looked = Option.getOrElse(found, () => new Map()) + const rowsByUrl = new Map([...remembered, ...looked]) + // Only a lookup that answered can say a URL has no map. + if (Option.isSome(found)) { + Arr.forEach(Array.from(looked), ([url, row]) => memo?.set(negativeKey(request, url), row)) + markNoMap( + Arr.map( + Arr.filter(pending, (url) => !rowsByUrl.has(url)), + (url) => negativeKey(request, url), + ), + now, + ) + } + + const matched = Arr.dedupeWith(Array.from(rowsByUrl.values()), (a, b) => a.id === b.id) + const tooLarge = Arr.filter(matched, (row) => row.sizeBytes > SYMBOLICATION_MAX_MAP_BYTES) + const rows = Arr.filter(matched, (row) => row.sizeBytes <= SYMBOLICATION_MAX_MAP_BYTES) + if (tooLarge.length > 0) { + yield* Effect.logWarning("Source maps too large to symbolicate with were skipped").pipe( + Effect.annotateLogs({ + orgId, + sourceMapIds: Arr.join( + Arr.map(tooLarge, (row) => row.id), + ",", + ), + limitBytes: SYMBOLICATION_MAX_MAP_BYTES, + }), + ) + } + // One at a time: each parse briefly holds the file, its string and the parsed map. Every + // loaded map stays live for the request, so past the budget the rest are left unloaded. + const estimate = (row: SourceMapFileRow) => row.sizeBytes * PARSED_MAP_SIZE_FACTOR + // Only rows taken count toward the budget: one left out does not crowd out a later small one. + const withinBudget = Arr.reduce( + rows, + { taken: Arr.empty(), planned: 0 }, + (plan, row) => + plan.taken.length === 0 || plan.planned + estimate(row) <= REQUEST_MAX_ESTIMATED_BYTES + ? { taken: [...plan.taken, row], planned: plan.planned + estimate(row) } + : plan, + ).taken + const overBudget = rows.length - withinBudget.length + if (overBudget > 0) { + yield* Effect.logWarning( + "Source maps over the per-stack memory budget were not loaded", + ).pipe(Effect.annotateLogs({ orgId, skipped: overBudget })) + } + const loaded = yield* Effect.forEach(withinBudget, (row) => + Effect.map(mapOf(row), (result) => ({ row, ...result })), + ) + // A map that could not be read is looked up again by the next stack, not reused. + if (memo !== undefined) { + const failed = new Set( + Arr.map( + Arr.filter(loaded, (entry) => entry.failed), + (entry) => entry.row.id, + ), + ) + Arr.forEach(Array.from(memo), ([key, row]) => { + if (failed.has(row.id)) memo.delete(key) + }) + } + const mapByFile = new Map( + Arr.getSomes( + Arr.map(loaded, ({ row, map }) => + Option.map(map, (value) => [row.id, value] as const), + ), + ), + ) + const lookup = (url: string): TraceMap | undefined => { + const row = rowsByUrl.get(url) + return row === undefined ? undefined : mapByFile.get(row.id) + } + + const symbolicated = Option.liftThrowable(() => + symbolicateStack( + stacktrace, + (frame) => (frame.url === null ? undefined : lookup(frame.url)), + request.debugIds, + ), + )() + if (Option.isNone(symbolicated)) { + yield* Effect.logWarning("Stack could not be symbolicated").pipe( + Effect.annotateLogs({ orgId }), + ) + } + const result = Option.getOrElse(symbolicated, () => + unresolvedStack(stacktrace, request.debugIds), + ) + + // Only a map that resolved a frame counts as used; frames line up with the parsed ones. + const usedIds = Arr.dedupe( + Arr.flatMap(result.frames, (frame, i) => { + const url = parsed.frames[i]?.url ?? null + const row = frame.resolved && url !== null ? rowsByUrl.get(url) : undefined + return row !== undefined && mapByFile.has(row.id) ? [row.id] : [] + }), + ) + yield* touchUsed(orgId, usedIds, now) + yield* Effect.annotateCurrentSpan({ + "maple.stack.status": result.status, + "maple.stack.resolved_frames": Arr.filter(result.frames, (frame) => frame.resolved) + .length, + "maple.stack.maps_matched": matched.length, + "maple.stack.maps_too_large": tooLarge.length, + "maple.stack.maps_over_budget": overBudget, + "maple.stack.maps_loaded": Arr.filter(loaded, (entry) => !entry.cacheHit).length, + "maple.stack.map_cache_hits": Arr.filter(loaded, (entry) => entry.cacheHit).length, + "maple.stack.negative_cache_hits": urls.length - pending.length, + }) + return { + stack: result, + lookupFailed: Option.isNone(found) || Arr.some(loaded, (entry) => entry.failed), + } satisfies SymbolicationOutcome + }) + + const symbolicate = (request: SymbolicateRequest) => + Effect.map(symbolicateWithOutcome(request), (outcome) => outcome.stack) + + return { + symbolicate, + symbolicateWithOutcome, + hasSourceMaps, + sourceMapsKnown, + } satisfies StackSymbolicatorApi + }), + }, +) { + static readonly layer = Layer.effect(this, this.make).pipe(Layer.provide(SourceMapReader.layer)) +} diff --git a/packages/backend/src/services/sourcemaps/source-map-files.ts b/packages/backend/src/services/sourcemaps/source-map-files.ts new file mode 100644 index 0000000000..ba83efce41 --- /dev/null +++ b/packages/backend/src/services/sourcemaps/source-map-files.ts @@ -0,0 +1,253 @@ +import { SOURCE_MAP_MAX_BYTES, SourceMapInvalidError, SourceMapTooLargeError } from "@maple/domain/http" +import type { OrgId, SourceMapFileId } from "@maple/primitives" +import { frameUrlPath, isSourceMappableUrl, urlMatchesMinifiedPath } from "@maple/domain/errors/js-stack" +import { Array as Arr, Effect, Option, Order, Predicate, Schema, String as Str } from "effect" + +/** + * Pure rules for stored source maps: what an upload must look like, and which stored file a stack + * frame URL belongs to. The service and its tests share them. + */ + +const MAX_PATH_LENGTH = 1024 +const MAX_LABEL_LENGTH = 256 +/** The release-path index entry must fit a B-tree page (~2.7 kB); multibyte text can exceed it. */ +const MAX_RELEASE_KEY_BYTES = 2000 + +/** Where a file's bytes live in the bucket; the org prefix is what org erasure deletes. */ +export const sourceMapObjectKey = (orgId: OrgId, id: SourceMapFileId): string => `v1/${orgId}/${id}` + +/** The prefix holding every source map of an org; the slash keeps `org_a` off `org_ab`. */ +export const sourceMapOrgPrefix = (orgId: OrgId): string => `v1/${orgId}/` + +const parseUrl = Option.liftThrowable((value: string) => new URL(value)) + +const stripLeadingSlashes = Str.replace(/^(?:\.\/|\/)+/u, "") + +/** `assets/a.js`, `/assets/a.js`, `./assets/a.js` and `https://cdn.test/assets/a.js` all store as `assets/a.js`. */ +export const normalizeMinifiedPath = (raw: string): string => + Option.match( + Option.filter( + parseUrl(Str.trim(raw)), + (url) => url.protocol === "http:" || url.protocol === "https:", + ), + { + onNone: () => stripLeadingSlashes(Str.trim(raw)), + // Frame paths are matched decoded, so a URL's percent-encoded path is stored decoded. + onSome: () => frameUrlPath(raw), + }, + ) + +const DEBUG_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u + +/** Debug ids compare lowercase; `None` when the value is not UUID-shaped. */ +export const normalizeDebugId = (raw: string): Option.Option => + Option.liftPredicate(Str.toLowerCase(Str.trim(raw)), (id) => DEBUG_ID_PATTERN.test(id)) + +const decodeJson = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown)) + +/** The parsed body when it is a JSON object; the text is dropped as soon as it is parsed. */ +const parseJsonObject = (bytes: Uint8Array) => + Option.filter(decodeJson(new TextDecoder().decode(bytes)), Predicate.isObject) + +export interface ValidatedSourceMap { + readonly minifiedPath: string + readonly debugId: string | null + readonly serviceName: string | null + readonly version: string | null + readonly sizeBytes: number + readonly hasSourcesContent: boolean +} + +export interface SourceMapUpload { + readonly bytes: Uint8Array + readonly minifiedPath: string + readonly debugId?: string | undefined + readonly serviceName?: string | undefined + readonly version?: string | undefined +} + +const invalid = (message: string, param?: string) => + new SourceMapInvalidError({ message, ...(param === undefined ? undefined : { param }) }) + +const optionalLabel = (value: string | undefined, param: string) => + Effect.gen(function* () { + if (value === undefined) return null + const trimmed = Str.trim(value) + if (trimmed.length === 0) return null + if (trimmed.length > MAX_LABEL_LENGTH) { + return yield* invalid(`\`${param}\` must be at most ${MAX_LABEL_LENGTH} characters.`, param) + } + return trimmed + }) + +const stringField = (fields: JsonObject, key: string): string | undefined => { + const value = fields[key] + return Predicate.isString(value) ? value : undefined +} + +type JsonObject = { readonly [x: PropertyKey]: unknown } + +/** An ignore list, when present, must be source indexes: the decoder calls array methods on it. */ +const isIgnoreList = (value: unknown): boolean => + value === undefined || + (Arr.isArray(value) && + Arr.every(value, (index) => Predicate.isNumber(index) && Number.isInteger(index) && index >= 0)) + +/** A plain map symbolication can read: a `mappings` string and at least one source (string or null). */ +const isRegularMap = (fields: JsonObject): boolean => { + const sources = fields["sources"] + return ( + isIgnoreList(fields["ignoreList"]) && + isIgnoreList(fields["x_google_ignoreList"]) && + Predicate.isString(fields["mappings"]) && + Arr.isArray(sources) && + sources.length > 0 && + Arr.every(sources, (source) => source === null || Predicate.isString(source)) + ) +} + +const hasContent = (fields: JsonObject): boolean => { + const sourcesContent = fields["sourcesContent"] + return ( + Arr.isArray(sourcesContent) && + Arr.some(sourcesContent, (content) => Predicate.isString(content) && content.length > 0) + ) +} + +/** + * Checks an upload against the contract: at most 10 MiB (what symbolication can load), a regular + * version 3 map (no index map) with a `mappings` string and sources, and a debug id or a service and version to find it by. A debug id the map itself carries + * (`debugId` / `debug_id`) is used when none is passed. + */ +export const validateSourceMapUpload = Effect.fn("SourceMapFiles.validateUpload")(function* ( + upload: SourceMapUpload, +) { + const sizeBytes = upload.bytes.byteLength + if (sizeBytes > SOURCE_MAP_MAX_BYTES) { + return yield* new SourceMapTooLargeError({ + message: `Source map is ${sizeBytes} bytes; the limit is ${SOURCE_MAP_MAX_BYTES} (10 MiB), the largest map Maple can symbolicate with.`, + sizeBytes, + }) + } + const minifiedPath = normalizeMinifiedPath(upload.minifiedPath) + if (minifiedPath.length === 0) { + return yield* invalid( + "`minified_path` must name the JavaScript file the map belongs to.", + "minified_path", + ) + } + if (minifiedPath.length > MAX_PATH_LENGTH) { + return yield* invalid( + `\`minified_path\` must be at most ${MAX_PATH_LENGTH} characters.`, + "minified_path", + ) + } + const serviceName = yield* optionalLabel(upload.serviceName, "service") + const version = yield* optionalLabel(upload.version, "version") + const keyBytes = new TextEncoder().encode( + `${serviceName ?? ""}${version ?? ""}${minifiedPath}`, + ).byteLength + if (keyBytes > MAX_RELEASE_KEY_BYTES) { + return yield* invalid( + `\`service\`, \`version\` and \`minified_path\` together must be at most ${MAX_RELEASE_KEY_BYTES} bytes.`, + "minified_path", + ) + } + + const fields = yield* Effect.fromOption(parseJsonObject(upload.bytes), () => + invalid("The body is not a JSON object."), + ) + if (fields["version"] !== 3) { + return yield* invalid("Only version 3 source maps are supported.") + } + // Any `sections` field makes it an index map, which symbolication does not read. + if (fields["sections"] !== undefined) { + return yield* invalid("Index source maps are not supported; emit a regular map.") + } + if (!isRegularMap(fields)) { + return yield* invalid( + "The source map needs a `mappings` string, a non-empty `sources` array and, if present, an `ignoreList` array of source indexes.", + ) + } + const hasSourcesContent = hasContent(fields) + + const rawDebugId = upload.debugId ?? stringField(fields, "debugId") ?? stringField(fields, "debug_id") + const debugId = + rawDebugId === undefined + ? null + : yield* Effect.fromOption(normalizeDebugId(rawDebugId), () => + invalid("`debug_id` must be a UUID.", "debug_id"), + ) + if (debugId === null && (serviceName === null || version === null)) { + return yield* invalid( + "Pass `debug_id`, or both `service` and `version`, so the map can be matched to stack traces.", + "debug_id", + ) + } + + return { + minifiedPath, + debugId, + serviceName, + version, + sizeBytes, + hasSourcesContent, + } satisfies ValidatedSourceMap +}) + +/** + * Whether a frame URL can have a stored map: a JS file or served URL, or any URL (a `blob:` one) + * the SDK recorded a valid debug id for. + */ +export const isLookupUrl = (url: string, debugIds: ReadonlyMap): boolean => + isSourceMappableUrl(url) || hasDebugIdFor(url, debugIds) + +/** Whether the SDK recorded a valid debug id for this frame URL. */ +export const hasDebugIdFor = (url: string, debugIds: ReadonlyMap): boolean => + Option.isSome(Option.flatMap(Option.fromNullishOr(debugIds.get(url)), normalizeDebugId)) + +/** The stored files a lookup can match: a debug id or a release (service + version) path. */ +export interface MatchableFile { + readonly debugId: string | null + readonly minifiedPath: string + readonly createdAt: number +} + +/** Longest path first; on a tie the map without a debug id (the release's own), then the newest. */ +const releaseFileOrder = () => + Order.combineAll([ + Order.mapInput(Order.flip(Order.Number), (file: F) => file.minifiedPath.length), + Order.mapInput(Order.Boolean, (file: F) => file.debugId !== null), + Order.mapInput(Order.flip(Order.Number), (file: F) => file.createdAt), + ]) + +/** + * Picks the file for each frame URL: the file its debug id names first, else the release file whose + * minified path the URL ends with (the longest such path when several do, see `releaseFileOrder`). + */ +export const matchFrames = ( + urls: ReadonlyArray, + debugIds: ReadonlyMap, + byDebugId: ReadonlyArray, + releaseFiles: ReadonlyArray, +): ReadonlyMap => + new Map( + Arr.flatMap(Arr.dedupe(urls), (url) => { + const fromDebugId = Option.flatMap( + Option.flatMap(Option.fromNullishOr(debugIds.get(url)), normalizeDebugId), + (id) => Arr.findFirst(byDebugId, (file) => file.debugId === id), + ) + const match = Option.orElse(fromDebugId, () => + Arr.head( + Arr.sort( + Arr.filter(releaseFiles, (file) => urlMatchesMinifiedPath(url, file.minifiedPath)), + releaseFileOrder(), + ), + ), + ) + return Option.match(match, { + onNone: () => [], + onSome: (file) => [[url, file] as const], + }) + }), + ) diff --git a/packages/backend/src/services/sourcemaps/symbolicate.test.ts b/packages/backend/src/services/sourcemaps/symbolicate.test.ts new file mode 100644 index 0000000000..d445dc9977 --- /dev/null +++ b/packages/backend/src/services/sourcemaps/symbolicate.test.ts @@ -0,0 +1,275 @@ +import { TraceMap } from "@jridgewell/trace-mapping" +import { Array as Arr } from "effect" +import { describe, expect, it } from "vitest" +import { symbolicateStack } from "./symbolicate" + +const BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" + +/** Base64 VLQ, as the source map v3 spec encodes each segment field. */ +const vlq = (value: number): string => { + const digits = (rest: number): ReadonlyArray => + rest < 32 ? [rest] : [(rest & 31) | 32, ...digits(rest >>> 5)] + return Arr.join( + Arr.map(digits(value < 0 ? (-value << 1) | 1 : value << 1), (digit) => BASE64[digit] ?? ""), + "", + ) +} + +type Segment = readonly [genColumn: number, source: number, line: number, column: number, name?: number] + +/** Encodes one generated line of absolute (0-based) segments into a `mappings` string. */ +const encodeLine = (segments: ReadonlyArray): string => + Arr.join( + Arr.map(segments, (segment, i) => { + const before = Arr.take(segments, i) + const previous = Arr.last(before) + const delta = (field: 0 | 1 | 2 | 3) => + segment[field] - (previous._tag === "Some" ? previous.value[field] : 0) + const fields = [delta(0), delta(1), delta(2), delta(3)] + const previousName = Arr.reduce(before, 0, (acc, s) => s[4] ?? acc) + const named = segment[4] === undefined ? fields : [...fields, segment[4] - previousName] + return Arr.join(Arr.map(named, vlq), "") + }), + ",", + ) + +const APP_SOURCE = Arr.join( + Arr.makeBy(14, (i) => `// app line ${i + 1}`), + "\n", +) + +// Generated line 1 of assets/index-Bx81.js: +// col 0 -> src/app.ts 7:0 named handleClick (the minified `a`) +// col 15 -> src/app.ts 9:9 +// col 30 -> node_modules/lib/index.js 2:4 +const appMap = new TraceMap({ + version: 3, + file: "index-Bx81.js", + sources: ["webpack://my-app/./src/app.ts", "webpack://my-app/./node_modules/lib/index.js"], + sourcesContent: [APP_SOURCE, null], + names: ["handleClick"], + mappings: encodeLine([ + [0, 0, 6, 0, 0], + [15, 0, 8, 9], + [30, 1, 1, 4], + ]), +}) + +// sourceRoot plus a relative source. +const chunkMap = new TraceMap({ + version: 3, + sourceRoot: "webpack://my-app/", + sources: ["./src/chunk.ts"], + names: [], + mappings: encodeLine([[0, 0, 2, 2]]), +}) + +const APP_URL = "https://app.example.com/assets/index-Bx81.js" +const CHUNK_URL = "https://app.example.com/assets/chunk-9a.js" +const UNMAPPED_URL = "https://app.example.com/assets/vendor-77.js" + +const lookup = (frame: { readonly url: string | null }) => + frame.url === APP_URL ? appMap : frame.url === CHUNK_URL ? chunkMap : undefined + +describe("symbolicateStack", () => { + it("maps a minified frame back to the original file and context", () => { + const result = symbolicateStack(`TypeError: boom\n at a (${APP_URL}:1:1)`, lookup) + expect(result.status).toBe("resolved") + expect(result.missing).toEqual([]) + expect(result.frames).toEqual([ + { + raw: `at a (${APP_URL}:1:1)`, + // No caller frame names it, so the minified name stays. + function: "a", + file: "src/app.ts", + line: 7, + column: 1, + in_app: true, + resolved: true, + context: { + pre: [ + "// app line 2", + "// app line 3", + "// app line 4", + "// app line 5", + "// app line 6", + ], + line: "// app line 7", + post: [ + "// app line 8", + "// app line 9", + "// app line 10", + "// app line 11", + "// app line 12", + ], + }, + }, + ]) + }) + + it("treats stack columns as 1-based and trace-mapping columns as 0-based", () => { + // 1-based column 16 is generated column 15, the second segment; column 15 still falls in the first. + const result = symbolicateStack( + `Error\n at a (${APP_URL}:1:16)\n at a (${APP_URL}:1:15)`, + lookup, + ) + expect( + Arr.map(result.frames, (frame) => [frame.function, frame.file, frame.line, frame.column]), + ).toEqual([ + // Named by the caller's call site (the `handleClick` token), not by its own position. + ["handleClick", "src/app.ts", 9, 10], + ["a", "src/app.ts", 7, 1], + ]) + expect(result.frames[0]?.context?.pre.length).toBe(5) + expect(result.frames[0]?.context?.line).toBe("// app line 9") + }) + + it("does not name a frame after the function it calls", () => { + const result = symbolicateStack( + `Error\n at a (${APP_URL}:1:1)\n at b (${APP_URL}:1:16)`, + lookup, + ) + expect(Arr.map(result.frames, (frame) => frame.function)).toEqual(["a", "b"]) + }) + + it("marks dependency frames as not in app and gives no context without sourcesContent", () => { + const [frame] = symbolicateStack(`Error\n at c (${APP_URL}:1:31)`, lookup).frames + expect(frame?.file).toBe("node_modules/lib/index.js") + expect([frame?.line, frame?.column]).toEqual([2, 5]) + expect(frame?.in_app).toBe(false) + expect(frame?.resolved).toBe(true) + expect(frame?.context).toBeNull() + }) + + it("resolves sources against sourceRoot", () => { + const [frame] = symbolicateStack(`Error\n at x (${CHUNK_URL}:1:1)`, lookup).frames + expect([frame?.file, frame?.line, frame?.column]).toEqual(["src/chunk.ts", 3, 3]) + }) + + it("reports partial with deduped missing URLs when some frames have no map", () => { + const result = symbolicateStack( + Arr.join( + [ + "Error: boom", + ` at a (${APP_URL}:1:1)`, + ` at v (${UNMAPPED_URL}:3:7)`, + ` at w (${UNMAPPED_URL}:4:1)`, + " at Array.map ()", + ], + "\n", + ), + lookup, + ) + expect(result.status).toBe("partial") + expect(result.missing).toEqual([UNMAPPED_URL]) + expect(result.frames[1]).toEqual({ + raw: `at v (${UNMAPPED_URL}:3:7)`, + function: "v", + file: UNMAPPED_URL, + line: 3, + column: 7, + in_app: true, + resolved: false, + context: null, + }) + expect(result.frames[3]?.in_app).toBe(false) + }) + + it("is resolved when only engine and dependency frames stay unmapped, and never lists them", () => { + const result = symbolicateStack( + Arr.join( + [ + "Error: boom", + ` at a (${APP_URL}:1:1)`, + " at process.processTicksAndRejections (node:internal/process/task_queues:95:5)", + " at run (/srv/app/node_modules/lib/index.js:10:3)", + " at Module._compile (node:internal/modules/cjs/loader:1256:14)", + ], + "\n", + ), + lookup, + ) + expect(result.status).toBe("resolved") + expect(result.missing).toEqual([]) + }) + + it("symbolicates Firefox frames", () => { + const result = symbolicateStack(`a@${APP_URL}:1:16\n@${UNMAPPED_URL}:1:1`, lookup) + expect(result.status).toBe("partial") + expect( + Arr.map(result.frames, (frame) => [frame.function, frame.file, frame.line, frame.column]), + ).toEqual([ + ["a", "src/app.ts", 9, 10], + [null, UNMAPPED_URL, 1, 1], + ]) + }) + + it("is missing_map when no frame resolves and not_applicable for non-JS stacks", () => { + expect(symbolicateStack(`Error\n at v (${UNMAPPED_URL}:3:7)`, lookup).status).toBe("missing_map") + const python = symbolicateStack('Traceback (most recent call last):\n File "a.py", line 1', lookup) + expect(python).toEqual({ status: "not_applicable", frames: [], missing: [] }) + }) + + it("keeps a mapped position whose source text the map leaves out", () => { + const short = new TraceMap({ + version: 3, + sources: ["src/app.ts"], + sourcesContent: [], + names: [], + mappings: "AAAA", + }) + const result = symbolicateStack(`Error\n at a (${APP_URL}:1:1)`, () => short) + expect(Arr.map(result.frames, (frame) => [frame.file, frame.line, frame.context])).toEqual([ + ["src/app.ts", 1, null], + ]) + }) + + it("leaves a zero-line frame raw and still maps the rest", () => { + const result = symbolicateStack(`Error\n at a (${APP_URL}:1:1)\n at b (${APP_URL}:0:1)`, lookup) + expect(Arr.map(result.frames, (frame) => frame.resolved)).toEqual([true, false]) + }) + + it("counts a locationless engine frame out of app", () => { + const result = symbolicateStack( + `Error\n at a (${APP_URL}:1:1)\n at processTick (native)`, + lookup, + ) + expect(Arr.map(result.frames, (frame) => frame.in_app)).toEqual([true, false]) + }) + + it("counts a source in the map's ignoreList out of app, still resolved", () => { + const ignoring = new TraceMap({ + version: 3, + sources: ["src/framework.js"], + names: [], + mappings: "AAAA", + ignoreList: [0], + }) + const [frame] = symbolicateStack(`Error\n at a (${APP_URL}:1:1)`, () => ignoring).frames + expect([frame?.file, frame?.resolved, frame?.in_app]).toEqual(["src/framework.js", true, false]) + }) + + it("does not name a frame after the frame below a Promise combinator", () => { + // b's position maps to a call of handleClick, but b called Promise.all, not a: a keeps its name. + const result = symbolicateStack( + `Error\n at a (${APP_URL}:1:1)\n at async Promise.all (index 0)\n at async b (${APP_URL}:1:1)`, + lookup, + ) + expect(Arr.map(result.frames, (frame) => [frame.function, frame.in_app])).toEqual([ + ["a", true], + ["Promise.all", false], + ["b", true], + ]) + }) + + it("counts a blob frame with a recorded debug id as one a map could resolve", () => { + const blob = "blob:https://app.example.com/0f3a9c1e-6b2d-4e8f-9a7c-1d2e3f4a5b6c" + const stack = `Error\n at a (${APP_URL}:1:1)\n at w (${blob}:1:1)` + const ids = new Map([[blob, "6c5e2b1a-1f2e-4d3c-8b7a-0123456789ab"]]) + const withId = symbolicateStack(stack, lookup, ids) + expect([withId.status, withId.missing]).toEqual(["partial", [blob]]) + expect(symbolicateStack(stack, lookup).status).toBe("resolved") + const blobOnly = symbolicateStack(`Error\n at w (${blob}:1:1)`, () => undefined, ids) + expect(blobOnly.status).toBe("missing_map") + }) +}) diff --git a/packages/backend/src/services/sourcemaps/symbolicate.ts b/packages/backend/src/services/sourcemaps/symbolicate.ts new file mode 100644 index 0000000000..fd1047bc16 --- /dev/null +++ b/packages/backend/src/services/sourcemaps/symbolicate.ts @@ -0,0 +1,138 @@ +import { + type ParsedFrame, + type StackFrame, + type StackFrameContext, + type SymbolicatedStack, + isInAppPath, + parseJsStack, +} from "@maple/domain/errors/js-stack" +import { type TraceMap, isIgnored, originalPositionFor, sourceContentFor } from "@jridgewell/trace-mapping" +import { Array as Arr, Predicate, String as Str } from "effect" +import { isLookupUrl } from "./source-map-files" + +const CONTEXT_LINES = 5 + +/** `webpack://my-app/./src/a.ts` and `../../src/a.ts` both read as `src/a.ts`. */ +export const displaySourcePath = (source: string): string => + Str.replace(/^(?:\.{1,2}\/)+/u, "")(Str.replace(/^webpack:\/\/[^/]*\//u, "")(source)) + +const contextFor = (map: TraceMap, source: string, line: number): StackFrameContext | null => { + // A short `sourcesContent` array leaves `undefined` where the type says string or null. + const content: unknown = sourceContentFor(map, source) + if (!Predicate.isString(content)) return null + const lines = Str.split(content, /\r?\n/u) + const index = line - 1 + const current = lines[index] + if (current === undefined) return null + return { + pre: lines.slice(Math.max(0, index - CONTEXT_LINES), index), + line: current, + post: lines.slice(index + 1, index + 1 + CONTEXT_LINES), + } +} + +const unresolved = (frame: ParsedFrame): StackFrame => ({ + raw: frame.raw, + function: frame.function, + file: frame.url, + line: frame.line, + column: frame.column, + // A frame with no location (`native`, ``) is the engine's, never the app's. + in_app: frame.url !== null && isInAppPath(frame.url), + resolved: false, + context: null, +}) + +interface MappedFrame { + readonly frame: StackFrame + /** The name a map gives the frame's position: at a call site, the name of the function called. */ + readonly callee: string | null +} + +const resolveFrame = (frame: ParsedFrame, map: TraceMap): MappedFrame => { + // trace-mapping throws below line 1; such a frame stays raw and the rest still map. + if (frame.line === null || !Number.isFinite(frame.line) || frame.line < 1) + return { frame: unresolved(frame), callee: null } + // Stack columns are 1-based, trace-mapping columns 0-based (lines are 1-based in both). + const position = originalPositionFor(map, { + line: frame.line, + column: Math.max(0, (frame.column ?? 1) - 1), + }) + if (position.source === null) return { frame: unresolved(frame), callee: null } + const file = displaySourcePath(position.source) + return { + frame: { + raw: frame.raw, + function: frame.function, + file, + line: position.line, + column: position.column + 1, + // The map's `ignoreList` marks framework and vendor sources out of app. + in_app: isInAppPath(file) && !isIgnored(map, position.source), + resolved: true, + context: contextFor(map, position.source, position.line), + }, + callee: position.name, + } +} + +/** + * A frame whose map the org could have uploaded: an in-app JS file or served URL, or any in-app + * URL its SDK recorded a debug id for (a `blob:` script). + */ +export const couldHaveSourceMap = ( + url: string | null, + debugIds: ReadonlyMap = NO_DEBUG_IDS, +): url is string => url !== null && isLookupUrl(url, debugIds) && isInAppPath(url) + +const NO_DEBUG_IDS: ReadonlyMap = new Map() + +/** + * Maps a JS stack trace through source maps. `lookup` returns the pre-loaded map for a frame, + * or undefined when none is stored; frames without a URL are never looked up. The status and + * `missing` count only frames that could have a map, so engine and dependency frames never + * make a stack partial. + */ +export const symbolicateStack = ( + stacktrace: string, + lookup: (frame: ParsedFrame) => TraceMap | undefined, + debugIds: ReadonlyMap = NO_DEBUG_IDS, +): SymbolicatedStack => { + const { frames: parsed } = parseJsStack(stacktrace) + const results = Arr.map(parsed, (frame) => { + const map = frame.url === null ? undefined : lookup(frame) + return { + mapped: map === undefined ? { frame: unresolved(frame), callee: null } : resolveFrame(frame, map), + candidate: couldHaveSourceMap(frame.url, debugIds), + } + }) + // A frame's own position names what it calls, so a resolved frame takes its name from the + // caller's call site (the next frame), else keeps the minified name. + const frames = Arr.map(results, (result, i) => { + const callerName = results[i + 1]?.mapped.callee ?? null + return result.mapped.frame.resolved && callerName !== null + ? { ...result.mapped.frame, function: callerName, function_from_map: true } + : result.mapped.frame + }) + const unresolvedCandidates = Arr.filter( + parsed, + (frame, i) => couldHaveSourceMap(frame.url, debugIds) && frames[i]?.resolved !== true, + ) + const missing = Arr.dedupe( + Arr.filter( + Arr.map(unresolvedCandidates, (frame) => frame.url), + (url) => url !== null, + ), + ) + const candidates = Arr.filter(results, (result) => result.candidate).length + const resolvedCount = Arr.filter(frames, (frame) => frame.resolved).length + const status: SymbolicatedStack["status"] = + frames.length === 0 || (candidates === 0 && resolvedCount === 0) + ? "not_applicable" + : resolvedCount === 0 + ? "missing_map" + : unresolvedCandidates.length === 0 + ? "resolved" + : "partial" + return { status, frames, missing } +} diff --git a/packages/browser/scripts/size.ts b/packages/browser/scripts/size.ts index 748c2bd99e..505831439d 100644 --- a/packages/browser/scripts/size.ts +++ b/packages/browser/scripts/size.ts @@ -91,8 +91,10 @@ const BUDGET = { * `errors.ignoreNetworkFailuresFor`, sampled-out sessions included (~0.55 kB). * 26.5 since 2026-11: `persistence: "cookieless"` (the row visitor rule, memory-wins * guard against older copies) measured 26.07 kB. + * 35.5 since 2026-11: main measured 34.97 kB; `maple.exception.debug_ids` (source map debug + * ids on every exception event, on the capture path) adds ~0.2 kB. */ - firstParty: 35, + firstParty: 35.5, } /** How close to a ceiling counts as worth warning about. */ diff --git a/packages/browser/src/__fixtures__/debug-id-chunk.js b/packages/browser/src/__fixtures__/debug-id-chunk.js new file mode 100644 index 0000000000..139bc4978b --- /dev/null +++ b/packages/browser/src/__fixtures__/debug-id-chunk.js @@ -0,0 +1,12 @@ +/* oxlint-disable */ +// A built chunk after `maple sourcemaps inject`: it throws for real, then carries the appended snippet. +window.__chunkError = Promise.resolve() + .then(function crash() { + throw new Error("from chunk") + }) + .catch(function (error) { + return error + }) +// prettier-ignore +!function(){try{var g="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},s=(new g.Error).stack;s&&(g._mapleDebugIds=g._mapleDebugIds||{},g._mapleDebugIds[s]="0b6c7a1e-58a4-4c1e-9d0b-2f3c4d5e6f70")}catch(e){}}() +//# debugId=0b6c7a1e-58a4-4c1e-9d0b-2f3c4d5e6f70 diff --git a/packages/browser/src/debug-ids.test.ts b/packages/browser/src/debug-ids.test.ts new file mode 100644 index 0000000000..9a47310768 --- /dev/null +++ b/packages/browser/src/debug-ids.test.ts @@ -0,0 +1,115 @@ +import { afterEach, describe, expect, it } from "vitest" +import { debugIdsOf, resetDebugIdsForTests } from "./debug-ids" +import { InMemorySpanExporter, SimpleSpanProcessor } from "./sdk/testing" +import { TracerProvider } from "./sdk/tracer" + +const owner: Record = globalThis + +const APP = "https://cdn.test/assets/app-1a2b.js" +const VENDOR = "https://cdn.test/assets/vendor-9f8e.js?v=3" +const APP_ID = "11111111-1111-4111-8111-111111111111" +const VENDOR_ID = "22222222-2222-4222-8222-222222222222" + +const v8Key = (url: string) => `Error\n at ${url}:1:345\n at https://cdn.test/assets/loader.js:9:9` + +afterEach(() => { + delete owner._mapleDebugIds + delete owner._sentryDebugIds + resetDebugIdsForTests() +}) + +describe("debugIdsOf", () => { + it("reads the file URL from V8, Firefox and Safari registration stacks", () => { + owner._mapleDebugIds = { + [v8Key(APP)]: APP_ID, + [`@${VENDOR}:1:12\n`]: VENDOR_ID, + "global code@https://cdn.test/assets/safari.js:1:88": "33333333-3333-4333-8333-333333333333", + } + const stack = [ + "TypeError: boom", + ` at render (${APP}:4:10)`, + `handler@${VENDOR}:2:3`, + "global code@https://cdn.test/assets/safari.js:7:1", + ].join("\n") + + expect(debugIdsOf(stack)).toBe( + JSON.stringify({ + [APP]: APP_ID, + [VENDOR]: VENDOR_ID, + "https://cdn.test/assets/safari.js": "33333333-3333-4333-8333-333333333333", + }), + ) + }) + + it("keeps a query string as part of the URL", () => { + owner._mapleDebugIds = { [v8Key(VENDOR)]: VENDOR_ID } + + expect(debugIdsOf(`Error\n at ${VENDOR}:1:1`)).toBe(JSON.stringify({ [VENDOR]: VENDOR_ID })) + expect(debugIdsOf("Error\n at https://cdn.test/assets/vendor-9f8e.js:1:1")).toBeUndefined() + }) + + it("includes only scripts that appear in the stack", () => { + owner._mapleDebugIds = { [v8Key(APP)]: APP_ID, [v8Key(VENDOR)]: VENDOR_ID } + + expect(debugIdsOf(`Error\n at f (${APP}:1:1)`)).toBe(JSON.stringify({ [APP]: APP_ID })) + expect(debugIdsOf("Error\n at f (https://cdn.test/other.js:1:1)")).toBeUndefined() + }) + + it("is absent when nothing is registered", () => { + expect(debugIdsOf(`Error\n at f (${APP}:1:1)`)).toBeUndefined() + }) + + it("picks up a chunk registered after the first lookup", () => { + const registry = { [v8Key(APP)]: APP_ID } + owner._mapleDebugIds = registry + const stack = `Error\n at f (${APP}:1:1)\n at g (${VENDOR}:1:1)` + expect(debugIdsOf(stack)).toBe(JSON.stringify({ [APP]: APP_ID })) + + registry[v8Key(VENDOR)] = VENDOR_ID + + expect(debugIdsOf(stack)).toBe(JSON.stringify({ [APP]: APP_ID, [VENDOR]: VENDOR_ID })) + }) + + it("reads Sentry's registry too, Maple's winning for the same script", () => { + owner._sentryDebugIds = { [v8Key(APP)]: "sentry-app", [v8Key(VENDOR)]: VENDOR_ID } + owner._mapleDebugIds = { [`${v8Key(APP)}\n at extra.js:1:1`]: APP_ID } + + expect(debugIdsOf(`Error\n at f (${APP}:1:1)\n at ${VENDOR}:2:2`)).toBe( + JSON.stringify({ + [APP]: APP_ID, + [VENDOR]: VENDOR_ID, + }), + ) + }) + + it("ignores malformed registries and entries", () => { + owner._sentryDebugIds = "not a registry" + owner._mapleDebugIds = { [v8Key(APP)]: 42, "no frames here": VENDOR_ID } + + expect(debugIdsOf(`Error\n at f (${APP}:1:1)`)).toBeUndefined() + }) +}) + +describe("recordException", () => { + it("puts the debug ids on the exception event", () => { + owner._mapleDebugIds = { [v8Key(APP)]: APP_ID } + const exporter = new InMemorySpanExporter() + const provider = new TracerProvider({ spanProcessors: [new SimpleSpanProcessor({ exporter })] }) + const span = provider.getTracer("test").startSpan("failure") + span.recordException({ + name: "TypeError", + message: "boom", + stack: `TypeError: boom\n at ${APP}:1:1`, + }) + span.recordException({ name: "TypeError", message: "elsewhere", stack: "TypeError\n at x.js:1:1" }) + span.end() + + const [registered, unregistered] = exporter.getFinishedSpans()[0]?.events ?? [] + expect(registered?.attributes?.["maple.exception.debug_ids"]).toBe( + JSON.stringify({ + [APP]: APP_ID, + }), + ) + expect(unregistered?.attributes).not.toHaveProperty("maple.exception.debug_ids") + }) +}) diff --git a/packages/browser/src/debug-ids.ts b/packages/browser/src/debug-ids.ts new file mode 100644 index 0000000000..e4c09db0ee --- /dev/null +++ b/packages/browser/src/debug-ids.ts @@ -0,0 +1,42 @@ +// Debug ids that `maple sourcemaps inject` (or Sentry's tooling) registers per script, keyed by +// a stack captured inside that script. The backend picks the source map by id, not by URL. +import { frameUrls } from "@maple/sdk-core" + +let registered = -1 +let byUrl = new Map() + +const isRecord = (value: unknown): value is Record => + typeof value === "object" && value !== null + +/** Script URL -> debug id, rebuilt when the registered count changes (chunks load lazily). */ +function debugIdsByUrl(): Map { + const owner: Record = globalThis + // Maple's registry last, so it wins over Sentry's for the same script. + const registries = [owner._sentryDebugIds, owner._mapleDebugIds].filter(isRecord) + // Counting keys allocates no entry pairs, so an unchanged registry costs little per exception. + const count = registries.reduce((total, registry) => total + Object.keys(registry).length, 0) + if (count !== registered) { + registered = count + byUrl = new Map() + for (const [stack, id] of registries.flatMap((registry) => Object.entries(registry))) { + const url = frameUrls(stack)[0] + if (url !== undefined && typeof id === "string") byUrl.set(url, id) + } + } + return byUrl +} + +/** `maple.exception.debug_ids` for `stack`: `{url: debugId}` JSON for each registered script in it. */ +export function debugIdsOf(stack: string): string | undefined { + const known = debugIdsByUrl() + const urls = known.size > 0 ? frameUrls(stack).filter((url) => known.has(url)) : [] + return urls.length > 0 + ? JSON.stringify(Object.fromEntries(urls.map((url) => [url, known.get(url)]))) + : undefined +} + +/** Test seam. */ +export function resetDebugIdsForTests(): void { + registered = -1 + byUrl = new Map() +} diff --git a/packages/browser/src/errors.browser.test.ts b/packages/browser/src/errors.browser.test.ts index 89e3cb7fc6..c6b15a049d 100644 --- a/packages/browser/src/errors.browser.test.ts +++ b/packages/browser/src/errors.browser.test.ts @@ -268,3 +268,29 @@ describe("filters and linked errors", () => { assert.include(String(stacktrace), "Caused by: TypeError: network down") }) }) + +describe("debug ids", () => { + it("records the debug id of a registered script the error was thrown from", async () => { + const url = new URL("./__fixtures__/debug-id-chunk.js", import.meta.url).href + const script = document.createElement("script") + script.src = url + await new Promise((resolve, reject) => { + script.addEventListener("load", resolve) + script.addEventListener("error", reject) + document.head.append(script) + }) + const owner: Record = globalThis + const error: unknown = await owner.__chunkError + + captureException(error) + + const event = exceptionEventOf(exporter.getFinishedSpans()[0]) + assert.include(String(event?.attributes?.["exception.stacktrace"]), url) + assert.deepEqual(JSON.parse(String(event?.attributes?.["maple.exception.debug_ids"])), { + [url]: "0b6c7a1e-58a4-4c1e-9d0b-2f3c4d5e6f70", + }) + script.remove() + delete owner._mapleDebugIds + delete owner.__chunkError + }) +}) diff --git a/packages/browser/src/sdk/span.ts b/packages/browser/src/sdk/span.ts index f2d7364da7..0cd28f9d21 100644 --- a/packages/browser/src/sdk/span.ts +++ b/packages/browser/src/sdk/span.ts @@ -15,6 +15,7 @@ import { SpanStatusCode, type TimeInput, } from "@opentelemetry/api" +import { debugIdsOf } from "../debug-ids" import { addAttribute, cleanAttributes } from "./attributes" import { addHrTimes, hrTime, hrTimeDuration, isHrTime, isTimeInput, millisToHrTime } from "./time" @@ -262,6 +263,8 @@ export class SpanImpl implements Span { } if (exception.stack !== undefined && exception.stack !== "") { attributes["exception.stacktrace"] = exception.stack + const debugIds = debugIdsOf(exception.stack) + if (debugIds !== undefined) attributes["maple.exception.debug_ids"] = debugIds } } if (attributes["exception.type"] !== undefined || attributes["exception.message"] !== undefined) { diff --git a/packages/db/drizzle/20261124140810_source_maps/migration.sql b/packages/db/drizzle/20261124140810_source_maps/migration.sql new file mode 100644 index 0000000000..69e2150013 --- /dev/null +++ b/packages/db/drizzle/20261124140810_source_maps/migration.sql @@ -0,0 +1,24 @@ +-- metadata +CREATE TABLE IF NOT EXISTS "source_map_files" ( + "id" text NOT NULL, + "org_id" text NOT NULL, + "debug_id" text, + "service_name" text, + "version" text, + "minified_path" text NOT NULL, + "size_bytes" integer NOT NULL, + "has_sources_content" boolean NOT NULL, + "object_key" text NOT NULL, + "created_at" timestamp with time zone NOT NULL DEFAULT now(), + "last_used_at" timestamp with time zone, + CONSTRAINT "source_map_files_pkey" PRIMARY KEY ("id") +); +--> statement-breakpoint +-- metadata +CREATE INDEX IF NOT EXISTS "source_map_files_org_created_idx" ON "source_map_files" USING btree ("org_id", "created_at"); +--> statement-breakpoint +-- metadata +CREATE UNIQUE INDEX IF NOT EXISTS "source_map_files_org_debug_id_idx" ON "source_map_files" USING btree ("org_id", "debug_id"); +--> statement-breakpoint +-- metadata +CREATE UNIQUE INDEX IF NOT EXISTS "source_map_files_org_release_path_idx" ON "source_map_files" USING btree ("org_id", "service_name", "version", "minified_path") WHERE "debug_id" IS NULL; diff --git a/packages/db/drizzle/20261124140810_source_maps/snapshot.json b/packages/db/drizzle/20261124140810_source_maps/snapshot.json new file mode 100644 index 0000000000..ad0406906f --- /dev/null +++ b/packages/db/drizzle/20261124140810_source_maps/snapshot.json @@ -0,0 +1,25647 @@ +{ + "version": "1", + "dialect": "postgres", + "id": "f10d98d49834a3f8ee51d4399eb3642a8ceff83f0b957da6df0c454f9657cfa0", + "prevIds": [ + "72ee25f4c58da443bfd76d1f3add40fc1da0dc97711ce10921d192f34939fd1a" + ], + "entities": [ + { + "kind": "table", + "name": "actors", + "primaryKey": { + "name": "actors_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "agent_feedback", + "primaryKey": { + "name": "agent_feedback_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "ai_triage_settings", + "primaryKey": { + "name": "ai_triage_settings_pkey", + "columns": [ + "org_id" + ] + } + }, + { + "kind": "table", + "name": "alert_delivery_events", + "primaryKey": { + "name": "alert_delivery_events_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "alert_destinations", + "primaryKey": { + "name": "alert_destinations_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "alert_escalation_runs", + "primaryKey": { + "name": "alert_escalation_runs_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "alert_incident_events", + "primaryKey": { + "name": "alert_incident_events_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "alert_incidents", + "primaryKey": { + "name": "alert_incidents_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "alert_linear_issues", + "primaryKey": { + "name": "alert_linear_issues_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "alert_maintenance_windows", + "primaryKey": { + "name": "alert_maintenance_windows_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "alert_member_notifications", + "primaryKey": { + "name": "alert_member_notifications_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "alert_rule_claims", + "primaryKey": { + "name": "alert_rule_claims_pkey", + "columns": [ + "rule_id" + ] + } + }, + { + "kind": "table", + "name": "alert_rule_states", + "primaryKey": { + "name": "alert_rule_states_org_id_rule_id_group_key_pk", + "columns": [ + "org_id", + "rule_id", + "group_key" + ] + } + }, + { + "kind": "table", + "name": "alert_rules", + "primaryKey": { + "name": "alert_rules_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "alert_silences", + "primaryKey": { + "name": "alert_silences_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "anomaly_detector_settings", + "primaryKey": { + "name": "anomaly_detector_settings_pkey", + "columns": [ + "org_id" + ] + } + }, + { + "kind": "table", + "name": "anomaly_detector_states", + "primaryKey": { + "name": "anomaly_detector_states_org_id_detector_key_pk", + "columns": [ + "org_id", + "detector_key" + ] + } + }, + { + "kind": "table", + "name": "anomaly_incidents", + "primaryKey": { + "name": "anomaly_incidents_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "api_keys", + "primaryKey": { + "name": "api_keys_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "aws_connections", + "primaryKey": { + "name": "aws_connections_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "cancellation_reviews", + "primaryKey": { + "name": "cancellation_reviews_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "chat_identities", + "primaryKey": { + "name": "chat_identities_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "chat_workspaces", + "primaryKey": { + "name": "chat_workspaces_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "cli_device_authorizations", + "primaryKey": { + "name": "cli_device_authorizations_pkey", + "columns": [ + "device_code_hash" + ] + } + }, + { + "kind": "table", + "name": "cloud_security_findings", + "primaryKey": { + "name": "cloud_security_findings_pkey", + "columns": [ + "org_id", + "connection_id", + "region", + "source", + "finding_id" + ] + } + }, + { + "kind": "table", + "name": "cloud_security_service_states", + "primaryKey": { + "name": "cloud_security_service_states_pkey", + "columns": [ + "org_id", + "connection_id", + "region", + "source" + ] + } + }, + { + "kind": "table", + "name": "cloudflare_analytics_state", + "primaryKey": { + "name": "cloudflare_analytics_state_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "cloudflare_feature_settings", + "primaryKey": { + "name": "cloudflare_feature_settings_pkey", + "columns": [ + "org_id" + ] + } + }, + { + "kind": "table", + "name": "cloudflare_hyperdrive_configs", + "primaryKey": { + "name": "cloudflare_hyperdrive_configs_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "cloudflare_logpush_connectors", + "primaryKey": { + "name": "cloudflare_logpush_connectors_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "cloudflare_zone_settings", + "primaryKey": { + "name": "cloudflare_zone_settings_pkey", + "columns": [ + "org_id", + "account_id" + ] + } + }, + { + "kind": "table", + "name": "cookieless_salts", + "primaryKey": { + "name": "cookieless_salts_pkey", + "columns": [ + "day" + ] + } + }, + { + "kind": "table", + "name": "cookieless_visits", + "primaryKey": { + "name": "cookieless_visits_pkey", + "columns": [ + "org_id", + "visitor_id" + ] + } + }, + { + "kind": "table", + "name": "cost_connections", + "primaryKey": { + "name": "cost_connections_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "cost_sources", + "primaryKey": { + "name": "cost_sources_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "dashboard_shares", + "primaryKey": { + "name": "dashboard_shares_org_id_id_pk", + "columns": [ + "org_id", + "id" + ] + } + }, + { + "kind": "table", + "name": "dashboard_versions", + "primaryKey": { + "name": "dashboard_versions_org_id_id_pk", + "columns": [ + "org_id", + "id" + ] + } + }, + { + "kind": "table", + "name": "dashboards", + "primaryKey": { + "name": "dashboards_org_id_id_pk", + "columns": [ + "org_id", + "id" + ] + } + }, + { + "kind": "table", + "name": "dependency_findings", + "primaryKey": { + "name": "dependency_findings_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "dependency_scan_matches", + "primaryKey": { + "name": "dependency_scan_matches_pkey", + "columns": [ + "scan_id", + "lockfile_path", + "ecosystem", + "package_name", + "version", + "advisory_id" + ] + } + }, + { + "kind": "table", + "name": "dependency_scans", + "primaryKey": { + "name": "dependency_scans_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "device_credentials", + "primaryKey": { + "name": "device_credentials_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "device_policy_findings", + "primaryKey": { + "name": "device_policy_findings_pkey", + "columns": [ + "org_id", + "source", + "connection_id", + "policy_id" + ] + } + }, + { + "kind": "table", + "name": "device_proof_replays", + "primaryKey": { + "name": "device_proof_replays_pkey", + "columns": [ + "key" + ] + } + }, + { + "kind": "table", + "name": "device_vulnerability_findings", + "primaryKey": { + "name": "device_vulnerability_findings_pkey", + "columns": [ + "org_id", + "source", + "connection_id", + "cve" + ] + } + }, + { + "kind": "table", + "name": "digest_subscriptions", + "primaryKey": { + "name": "digest_subscriptions_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "error_fingerprint_candidates", + "primaryKey": { + "name": "error_fingerprint_candidates_org_id_fingerprint_hash_pk", + "columns": [ + "org_id", + "fingerprint_hash" + ] + } + }, + { + "kind": "table", + "name": "error_grouping_configs", + "primaryKey": { + "name": "error_grouping_configs_pkey", + "columns": [ + "org_id" + ] + } + }, + { + "kind": "table", + "name": "error_grouping_keys", + "primaryKey": { + "name": "error_grouping_keys_org_id_fingerprint_hash_pk", + "columns": [ + "org_id", + "fingerprint_hash" + ] + } + }, + { + "kind": "table", + "name": "error_incidents", + "primaryKey": { + "name": "error_incidents_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "error_issue_events", + "primaryKey": { + "name": "error_issue_events_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "error_issue_fingerprints", + "primaryKey": { + "name": "error_issue_fingerprints_org_id_fingerprint_hash_pk", + "columns": [ + "org_id", + "fingerprint_hash" + ] + } + }, + { + "kind": "table", + "name": "error_issue_pull_requests", + "primaryKey": { + "name": "error_issue_pull_requests_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "error_issue_states", + "primaryKey": { + "name": "error_issue_states_org_id_issue_id_pk", + "columns": [ + "org_id", + "issue_id" + ] + } + }, + { + "kind": "table", + "name": "error_issue_verifications", + "primaryKey": { + "name": "error_issue_verifications_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "error_issues", + "primaryKey": { + "name": "error_issues_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "error_notification_deliveries", + "primaryKey": { + "name": "error_notification_deliveries_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "error_notification_policies", + "primaryKey": { + "name": "error_notification_policies_pkey", + "columns": [ + "org_id" + ] + } + }, + { + "kind": "table", + "name": "error_tick_states", + "primaryKey": { + "name": "error_tick_states_pkey", + "columns": [ + "org_id" + ] + } + }, + { + "kind": "table", + "name": "escalation_chains", + "primaryKey": { + "name": "escalation_chains_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "external_data_source_catalog_entries", + "primaryKey": { + "name": "external_data_source_catalog_entries_pk", + "columns": [ + "source_id", + "name" + ] + } + }, + { + "kind": "table", + "name": "external_data_sources", + "primaryKey": { + "name": "external_data_sources_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "feature_requests", + "primaryKey": { + "name": "feature_requests_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "fleet_connections", + "primaryKey": { + "name": "fleet_connections_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "gcp_connectors", + "primaryKey": { + "name": "gcp_connectors_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "gcp_cost_exports", + "primaryKey": { + "name": "gcp_cost_exports_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "gcp_resources", + "primaryKey": { + "name": "gcp_resources_pkey", + "columns": [ + "connector_id", + "name" + ] + } + }, + { + "kind": "table", + "name": "investigations", + "primaryKey": { + "name": "investigations_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "issue_escalation_policies", + "primaryKey": { + "name": "issue_escalation_policies_pkey", + "columns": [ + "org_id" + ] + } + }, + { + "kind": "table", + "name": "issue_escalations", + "primaryKey": { + "name": "issue_escalations_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "linear_feature_settings", + "primaryKey": { + "name": "linear_feature_settings_pkey", + "columns": [ + "org_id" + ] + } + }, + { + "kind": "table", + "name": "live_activities", + "primaryKey": { + "name": "live_activities_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "mcp_oauth_authorizations", + "primaryKey": { + "name": "mcp_oauth_authorizations_pkey", + "columns": [ + "request_id_hash" + ] + } + }, + { + "kind": "table", + "name": "mcp_oauth_clients", + "primaryKey": { + "name": "mcp_oauth_clients_pkey", + "columns": [ + "client_id" + ] + } + }, + { + "kind": "table", + "name": "mcp_oauth_refresh_tokens", + "primaryKey": { + "name": "mcp_oauth_refresh_tokens_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "mobile_devices", + "primaryKey": { + "name": "mobile_devices_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "oauth_auth_states", + "primaryKey": { + "name": "oauth_auth_states_pkey", + "columns": [ + "state" + ] + } + }, + { + "kind": "table", + "name": "oauth_connections", + "primaryKey": { + "name": "oauth_connections_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "onboarding_agent_runs", + "primaryKey": { + "name": "onboarding_agent_runs_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "oncall_overrides", + "primaryKey": { + "name": "oncall_overrides_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "oncall_schedules", + "primaryKey": { + "name": "oncall_schedules_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "openrouter_cost_connections", + "primaryKey": { + "name": "openrouter_cost_connections_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "org_billing_links", + "primaryKey": { + "name": "org_billing_links_pkey", + "columns": [ + "org_id" + ] + } + }, + { + "kind": "table", + "name": "org_clickhouse_schema_apply_runs", + "primaryKey": { + "name": "org_clickhouse_schema_apply_runs_org_id_pk", + "columns": [ + "org_id" + ] + } + }, + { + "kind": "table", + "name": "org_clickhouse_settings", + "primaryKey": { + "name": "org_clickhouse_settings_org_id_pk", + "columns": [ + "org_id" + ] + } + }, + { + "kind": "table", + "name": "org_directory_groups", + "primaryKey": { + "name": "org_directory_groups_pkey", + "columns": [ + "directory_id", + "group_id" + ] + } + }, + { + "kind": "table", + "name": "org_erasures", + "primaryKey": { + "name": "org_erasures_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "org_ingest_attribute_mappings", + "primaryKey": { + "name": "org_ingest_attribute_mappings_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "org_ingest_keys", + "primaryKey": { + "name": "org_ingest_keys_org_id_pk", + "columns": [ + "org_id" + ] + } + }, + { + "kind": "table", + "name": "org_ingest_rule_settings", + "primaryKey": { + "name": "org_ingest_rule_settings_pkey", + "columns": [ + "org_id" + ] + } + }, + { + "kind": "table", + "name": "org_ingest_rule_stats", + "primaryKey": { + "name": "org_ingest_rule_stats_pkey", + "columns": [ + "org_id", + "rule_id", + "bucket", + "signal" + ] + } + }, + { + "kind": "table", + "name": "org_ingest_rules", + "primaryKey": { + "name": "org_ingest_rules_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "org_ingest_sampling_policies", + "primaryKey": { + "name": "org_ingest_sampling_policies_pkey", + "columns": [ + "org_id" + ] + } + }, + { + "kind": "table", + "name": "org_onboarding_state", + "primaryKey": { + "name": "org_onboarding_state_pkey", + "columns": [ + "org_id" + ] + } + }, + { + "kind": "table", + "name": "org_openrouter_keys", + "primaryKey": { + "name": "org_openrouter_keys_pkey", + "columns": [ + "org_id" + ] + } + }, + { + "kind": "table", + "name": "org_recommendation_issues", + "primaryKey": { + "name": "org_recommendation_issues_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "org_sso_connections", + "primaryKey": { + "name": "org_sso_connections_pkey", + "columns": [ + "org_id" + ] + } + }, + { + "kind": "table", + "name": "org_sso_domains", + "primaryKey": { + "name": "org_sso_domains_pkey", + "columns": [ + "org_id", + "domain" + ] + } + }, + { + "kind": "table", + "name": "org_support_channels", + "primaryKey": { + "name": "org_support_channels_pkey", + "columns": [ + "org_id" + ] + } + }, + { + "kind": "table", + "name": "planetscale_connections", + "primaryKey": { + "name": "planetscale_connections_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "planetscale_databases", + "primaryKey": { + "name": "planetscale_databases_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "planetscale_events", + "primaryKey": { + "name": "planetscale_events_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "planetscale_issue_receipts", + "primaryKey": { + "name": "planetscale_issue_receipts_org_id_event_id_pk", + "columns": [ + "org_id", + "event_id" + ] + } + }, + { + "kind": "table", + "name": "planetscale_poll_state", + "primaryKey": { + "name": "planetscale_poll_state_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "pr_review_edits", + "primaryKey": { + "name": "pr_review_edits_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "pr_review_finding_embeddings", + "primaryKey": { + "name": "pr_review_finding_embeddings_pkey", + "columns": [ + "finding_id" + ] + } + }, + { + "kind": "table", + "name": "pr_review_findings", + "primaryKey": { + "name": "pr_review_findings_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "pr_review_merge_steps", + "primaryKey": { + "name": "pr_review_merge_steps_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "pr_review_replies", + "primaryKey": { + "name": "pr_review_replies_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "pr_review_settings", + "primaryKey": { + "name": "pr_review_settings_pkey", + "columns": [ + "org_id" + ] + } + }, + { + "kind": "table", + "name": "pr_reviews", + "primaryKey": { + "name": "pr_reviews_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "railway_connections", + "primaryKey": { + "name": "railway_connections_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "railway_environments", + "primaryKey": { + "name": "railway_environments_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "saved_views", + "primaryKey": { + "name": "saved_views_org_id_id_pk", + "columns": [ + "org_id", + "id" + ] + } + }, + { + "kind": "table", + "name": "scrape_target_checks", + "primaryKey": { + "name": "scrape_target_checks_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "scrape_targets", + "primaryKey": { + "name": "scrape_targets_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "search_console_sites", + "primaryKey": { + "name": "search_console_sites_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "security_audit_events", + "primaryKey": { + "name": "security_audit_events_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "security_audit_findings", + "primaryKey": { + "name": "security_audit_findings_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "security_audit_org_reservations", + "primaryKey": { + "name": "security_audit_org_reservations_pkey", + "columns": [ + "run_id", + "agent_id" + ] + } + }, + { + "kind": "table", + "name": "security_audit_org_settings", + "primaryKey": { + "name": "security_audit_org_settings_pkey", + "columns": [ + "org_id" + ] + } + }, + { + "kind": "table", + "name": "security_audit_run_findings", + "primaryKey": { + "name": "security_audit_run_findings_pkey", + "columns": [ + "run_id", + "fingerprint" + ] + } + }, + { + "kind": "table", + "name": "security_audit_runs", + "primaryKey": { + "name": "security_audit_runs_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "security_audit_targets", + "primaryKey": { + "name": "security_audit_targets_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "security_audit_units", + "primaryKey": { + "name": "security_audit_units_pkey", + "columns": [ + "run_id", + "coverage_id" + ] + } + }, + { + "kind": "table", + "name": "service_map_world_entities", + "primaryKey": { + "name": "service_map_world_entities_pkey", + "columns": [ + "org_id", + "entity_id" + ] + } + }, + { + "kind": "table", + "name": "slos", + "primaryKey": { + "name": "slos_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "source_map_files", + "primaryKey": { + "name": "source_map_files_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "sources", + "primaryKey": { + "name": "sources_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "status_page_cleanups", + "primaryKey": { + "name": "status_page_cleanups_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "status_page_components", + "primaryKey": { + "name": "status_page_components_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "status_page_custom_domains", + "primaryKey": { + "name": "status_page_custom_domains_pkey", + "columns": [ + "page_id" + ] + } + }, + { + "kind": "table", + "name": "status_page_incident_components", + "primaryKey": { + "name": "status_page_incident_components_pk", + "columns": [ + "incident_id", + "component_id" + ] + } + }, + { + "kind": "table", + "name": "status_page_incident_updates", + "primaryKey": { + "name": "status_page_incident_updates_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "status_page_incidents", + "primaryKey": { + "name": "status_page_incidents_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "status_pages", + "primaryKey": { + "name": "status_pages_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "supabase_connections", + "primaryKey": { + "name": "supabase_connections_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "supabase_project_insights", + "primaryKey": { + "name": "supabase_project_insights_pkey", + "columns": [ + "project_id" + ] + } + }, + { + "kind": "table", + "name": "supabase_projects", + "primaryKey": { + "name": "supabase_projects_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "uptime_monitor_daily", + "primaryKey": { + "name": "uptime_monitor_daily_pk", + "columns": [ + "monitor_id", + "day" + ] + } + }, + { + "kind": "table", + "name": "uptime_monitor_states", + "primaryKey": { + "name": "uptime_monitor_states_pkey", + "columns": [ + "monitor_id" + ] + } + }, + { + "kind": "table", + "name": "uptime_monitors", + "primaryKey": { + "name": "uptime_monitors_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "vcs_commits", + "primaryKey": { + "name": "vcs_commits_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "vcs_installations", + "primaryKey": { + "name": "vcs_installations_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "vcs_repositories", + "primaryKey": { + "name": "vcs_repositories_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "vcs_repository_branches", + "primaryKey": { + "name": "vcs_repository_branches_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "vercel_connections", + "primaryKey": { + "name": "vercel_connections_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "vercel_deployments", + "primaryKey": { + "name": "vercel_deployments_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "table", + "name": "vercel_projects", + "primaryKey": { + "name": "vercel_projects_pkey", + "columns": [ + "id" + ] + } + }, + { + "kind": "column", + "table": "actors", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "actors", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "actors", + "name": "type", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "actors", + "name": "user_id", + "position": 3, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "actors", + "name": "agent_name", + "position": 4, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "actors", + "name": "model", + "position": 5, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "actors", + "name": "capabilities_json", + "position": 6, + "type": "jsonb", + "notNull": true, + "default": "'[]'", + "identity": null + }, + { + "kind": "column", + "table": "actors", + "name": "created_by", + "position": 7, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "actors", + "name": "created_at", + "position": 8, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "actors", + "name": "last_active_at", + "position": 9, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "agent_feedback", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "agent_feedback", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "agent_feedback", + "name": "user_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "agent_feedback", + "name": "kind", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "agent_feedback", + "name": "impact", + "position": 4, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "agent_feedback", + "name": "summary", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "agent_feedback", + "name": "reason", + "position": 6, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "agent_feedback", + "name": "details", + "position": 7, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "agent_feedback", + "name": "related_to", + "position": 8, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "agent_feedback", + "name": "agent_type", + "position": 9, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "agent_feedback", + "name": "agent_name", + "position": 10, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "agent_feedback", + "name": "agent_model", + "position": 11, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "agent_feedback", + "name": "agent_version", + "position": 12, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "agent_feedback", + "name": "source", + "position": 13, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "agent_feedback", + "name": "created_at", + "position": 14, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "ai_triage_settings", + "name": "org_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "ai_triage_settings", + "name": "enabled", + "position": 1, + "type": "boolean", + "notNull": true, + "default": "false", + "identity": null + }, + { + "kind": "column", + "table": "ai_triage_settings", + "name": "max_runs_per_day", + "position": 2, + "type": "integer", + "notNull": true, + "default": "20", + "identity": null + }, + { + "kind": "column", + "table": "ai_triage_settings", + "name": "max_passes_per_day", + "position": 3, + "type": "integer", + "notNull": true, + "default": "90", + "identity": null + }, + { + "kind": "column", + "table": "ai_triage_settings", + "name": "updated_at", + "position": 4, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "ai_triage_settings", + "name": "updated_by", + "position": 5, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_delivery_events", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_delivery_events", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_delivery_events", + "name": "incident_id", + "position": 2, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_delivery_events", + "name": "rule_id", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_delivery_events", + "name": "destination_id", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_delivery_events", + "name": "delivery_key", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_delivery_events", + "name": "event_type", + "position": 6, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_delivery_events", + "name": "attempt_number", + "position": 7, + "type": "integer", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_delivery_events", + "name": "status", + "position": 8, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_delivery_events", + "name": "scheduled_at", + "position": 9, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_delivery_events", + "name": "claimed_at", + "position": 10, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_delivery_events", + "name": "claim_expires_at", + "position": 11, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_delivery_events", + "name": "claimed_by", + "position": 12, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_delivery_events", + "name": "attempted_at", + "position": 13, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_delivery_events", + "name": "provider_message", + "position": 14, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_delivery_events", + "name": "provider_reference", + "position": 15, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_delivery_events", + "name": "response_code", + "position": 16, + "type": "integer", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_delivery_events", + "name": "error_message", + "position": 17, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_delivery_events", + "name": "silence_id", + "position": 18, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_delivery_events", + "name": "payload_json", + "position": 19, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_delivery_events", + "name": "created_at", + "position": 20, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_delivery_events", + "name": "updated_at", + "position": 21, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_destinations", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_destinations", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_destinations", + "name": "name", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_destinations", + "name": "type", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_destinations", + "name": "enabled", + "position": 4, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "alert_destinations", + "name": "config_json", + "position": 5, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_destinations", + "name": "secret_ciphertext", + "position": 6, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_destinations", + "name": "secret_iv", + "position": 7, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_destinations", + "name": "secret_tag", + "position": 8, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_destinations", + "name": "last_tested_at", + "position": 9, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_destinations", + "name": "last_test_error", + "position": 10, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_destinations", + "name": "consecutive_failures", + "position": 11, + "type": "integer", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "alert_destinations", + "name": "last_failure_at", + "position": 12, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_destinations", + "name": "disabled_at", + "position": 13, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_destinations", + "name": "disabled_reason", + "position": 14, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_destinations", + "name": "created_at", + "position": 15, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_destinations", + "name": "updated_at", + "position": 16, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_destinations", + "name": "created_by", + "position": 17, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_destinations", + "name": "updated_by", + "position": 18, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_escalation_runs", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_escalation_runs", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_escalation_runs", + "name": "incident_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_escalation_runs", + "name": "chain_id", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_escalation_runs", + "name": "chain_name", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_escalation_runs", + "name": "severity", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_escalation_runs", + "name": "steps_json", + "position": 6, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_escalation_runs", + "name": "repeat_count", + "position": 7, + "type": "integer", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_escalation_runs", + "name": "step_index", + "position": 8, + "type": "integer", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "alert_escalation_runs", + "name": "pass_index", + "position": 9, + "type": "integer", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "alert_escalation_runs", + "name": "next_step_at", + "position": 10, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_escalation_runs", + "name": "status", + "position": 11, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_escalation_runs", + "name": "payload_json", + "position": 12, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_escalation_runs", + "name": "steps_sent", + "position": 13, + "type": "integer", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "alert_escalation_runs", + "name": "last_step_at", + "position": 14, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_escalation_runs", + "name": "ended_at", + "position": 15, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_escalation_runs", + "name": "created_at", + "position": 16, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_escalation_runs", + "name": "updated_at", + "position": 17, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incident_events", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incident_events", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incident_events", + "name": "incident_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incident_events", + "name": "type", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incident_events", + "name": "actor_user_id", + "position": 4, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incident_events", + "name": "actor_name", + "position": 5, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incident_events", + "name": "source", + "position": 6, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incident_events", + "name": "detail", + "position": 7, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incident_events", + "name": "created_at", + "position": 8, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incidents", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incidents", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incidents", + "name": "rule_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incidents", + "name": "incident_key", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incidents", + "name": "rule_name", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incidents", + "name": "group_key", + "position": 5, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incidents", + "name": "signal_type", + "position": 6, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incidents", + "name": "severity", + "position": 7, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incidents", + "name": "peak_severity", + "position": 8, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incidents", + "name": "status", + "position": 9, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incidents", + "name": "comparator", + "position": 10, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incidents", + "name": "threshold", + "position": 11, + "type": "double precision", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incidents", + "name": "threshold_upper", + "position": 12, + "type": "double precision", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incidents", + "name": "first_triggered_at", + "position": 13, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incidents", + "name": "last_triggered_at", + "position": 14, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incidents", + "name": "resolved_at", + "position": 15, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incidents", + "name": "last_observed_value", + "position": 16, + "type": "double precision", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incidents", + "name": "last_sample_count", + "position": 17, + "type": "integer", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incidents", + "name": "last_evaluated_at", + "position": 18, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incidents", + "name": "dedupe_key", + "position": 19, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incidents", + "name": "last_delivered_event_type", + "position": 20, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incidents", + "name": "last_notified_at", + "position": 21, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incidents", + "name": "hold_reason", + "position": 22, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incidents", + "name": "held_since", + "position": 23, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incidents", + "name": "acknowledged_at", + "position": 24, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incidents", + "name": "acknowledged_by_user_id", + "position": 25, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incidents", + "name": "acknowledged_by_name", + "position": 26, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incidents", + "name": "acknowledged_via", + "position": 27, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incidents", + "name": "first_acknowledged_at", + "position": 28, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incidents", + "name": "quiet_since", + "position": 29, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incidents", + "name": "error_issue_id", + "position": 30, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incidents", + "name": "anomaly_incident_id", + "position": 31, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incidents", + "name": "group_label", + "position": 32, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incidents", + "name": "labels_json", + "position": 33, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incidents", + "name": "silence_id", + "position": 34, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incidents", + "name": "silenced_at", + "position": 35, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incidents", + "name": "created_at", + "position": 36, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_incidents", + "name": "updated_at", + "position": 37, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_linear_issues", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_linear_issues", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_linear_issues", + "name": "destination_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_linear_issues", + "name": "thread_key", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_linear_issues", + "name": "linear_team_id", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_linear_issues", + "name": "linear_issue_id", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_linear_issues", + "name": "linear_identifier", + "position": 6, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_linear_issues", + "name": "linear_url", + "position": 7, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_linear_issues", + "name": "incident_id", + "position": 8, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_linear_issues", + "name": "created_at", + "position": 9, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_linear_issues", + "name": "updated_at", + "position": 10, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_maintenance_windows", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_maintenance_windows", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_maintenance_windows", + "name": "name", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_maintenance_windows", + "name": "reason", + "position": 3, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_maintenance_windows", + "name": "matchers_json", + "position": 4, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_maintenance_windows", + "name": "schedule_json", + "position": 5, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_maintenance_windows", + "name": "exclude_from_baselines", + "position": 6, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "alert_maintenance_windows", + "name": "enabled", + "position": 7, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "alert_maintenance_windows", + "name": "once_ends_at", + "position": 8, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_maintenance_windows", + "name": "revision", + "position": 9, + "type": "integer", + "notNull": true, + "default": "1", + "identity": null + }, + { + "kind": "column", + "table": "alert_maintenance_windows", + "name": "created_at", + "position": 10, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_maintenance_windows", + "name": "updated_at", + "position": 11, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_maintenance_windows", + "name": "created_by", + "position": 12, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_maintenance_windows", + "name": "updated_by", + "position": 13, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_member_notifications", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_member_notifications", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_member_notifications", + "name": "incident_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_member_notifications", + "name": "run_id", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_member_notifications", + "name": "user_id", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_member_notifications", + "name": "channel", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_member_notifications", + "name": "status", + "position": 6, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_member_notifications", + "name": "attempt_number", + "position": 7, + "type": "integer", + "notNull": true, + "default": "1", + "identity": null + }, + { + "kind": "column", + "table": "alert_member_notifications", + "name": "scheduled_at", + "position": 8, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_member_notifications", + "name": "claimed_at", + "position": 9, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_member_notifications", + "name": "claim_expires_at", + "position": 10, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_member_notifications", + "name": "payload_json", + "position": 11, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_member_notifications", + "name": "dedupe_key", + "position": 12, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_member_notifications", + "name": "error_message", + "position": 13, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_member_notifications", + "name": "attempted_at", + "position": 14, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_member_notifications", + "name": "created_at", + "position": 15, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_member_notifications", + "name": "updated_at", + "position": 16, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rule_claims", + "name": "rule_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rule_claims", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rule_claims", + "name": "last_scheduled_at", + "position": 2, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rule_claims", + "name": "consecutive_limit_failures", + "position": 3, + "type": "integer", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "alert_rule_states", + "name": "org_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rule_states", + "name": "rule_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rule_states", + "name": "group_key", + "position": 2, + "type": "text", + "notNull": true, + "default": "'__total__'", + "identity": null + }, + { + "kind": "column", + "table": "alert_rule_states", + "name": "consecutive_breaches", + "position": 3, + "type": "integer", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "alert_rule_states", + "name": "consecutive_healthy", + "position": 4, + "type": "integer", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "alert_rule_states", + "name": "history_json", + "position": 5, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rule_states", + "name": "last_status", + "position": 6, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rule_states", + "name": "last_value", + "position": 7, + "type": "double precision", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rule_states", + "name": "last_sample_count", + "position": 8, + "type": "integer", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rule_states", + "name": "last_evaluated_at", + "position": 9, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rule_states", + "name": "last_error", + "position": 10, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rule_states", + "name": "last_error_kind", + "position": 11, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rule_states", + "name": "updated_at", + "position": 12, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rules", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rules", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rules", + "name": "name", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rules", + "name": "notes", + "position": 3, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rules", + "name": "notification_template_json", + "position": 4, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rules", + "name": "enabled", + "position": 5, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "alert_rules", + "name": "severity", + "position": 6, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rules", + "name": "service_names_json", + "position": 7, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rules", + "name": "exclude_service_names_json", + "position": 8, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rules", + "name": "environments_json", + "position": 9, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rules", + "name": "anomaly_signals_json", + "position": 10, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rules", + "name": "audit_filters_json", + "position": 11, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rules", + "name": "audit_count_from", + "position": 12, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rules", + "name": "cost_budget_json", + "position": 13, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rules", + "name": "tags_json", + "position": 14, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rules", + "name": "signal_type", + "position": 15, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rules", + "name": "comparator", + "position": 16, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rules", + "name": "threshold", + "position": 17, + "type": "double precision", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rules", + "name": "threshold_upper", + "position": 18, + "type": "double precision", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rules", + "name": "thresholds_json", + "position": 19, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rules", + "name": "window_minutes", + "position": 20, + "type": "integer", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rules", + "name": "evaluation_interval_minutes", + "position": 21, + "type": "integer", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rules", + "name": "slowed_interval_minutes", + "position": 22, + "type": "integer", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rules", + "name": "slowed_at", + "position": 23, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rules", + "name": "minimum_sample_count", + "position": 24, + "type": "integer", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "alert_rules", + "name": "consecutive_breaches_required", + "position": 25, + "type": "integer", + "notNull": true, + "default": "2", + "identity": null + }, + { + "kind": "column", + "table": "alert_rules", + "name": "breaches_out_of", + "position": 26, + "type": "integer", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rules", + "name": "consecutive_healthy_required", + "position": 27, + "type": "integer", + "notNull": true, + "default": "2", + "identity": null + }, + { + "kind": "column", + "table": "alert_rules", + "name": "renotify_interval_minutes", + "position": 28, + "type": "integer", + "notNull": true, + "default": "30", + "identity": null + }, + { + "kind": "column", + "table": "alert_rules", + "name": "apdex_threshold_ms", + "position": 29, + "type": "double precision", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rules", + "name": "query_builder_draft_json", + "position": 30, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rules", + "name": "raw_query_sql", + "position": 31, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rules", + "name": "group_by", + "position": 32, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rules", + "name": "destination_ids_json", + "position": 33, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rules", + "name": "query_spec_json", + "position": 34, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rules", + "name": "reducer", + "position": 35, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rules", + "name": "sample_count_strategy", + "position": 36, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rules", + "name": "no_data_behavior", + "position": 37, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rules", + "name": "last_scheduled_at", + "position": 38, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rules", + "name": "created_at", + "position": 39, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rules", + "name": "updated_at", + "position": 40, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rules", + "name": "created_by", + "position": 41, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_rules", + "name": "updated_by", + "position": 42, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_silences", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_silences", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_silences", + "name": "reason", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_silences", + "name": "matchers_json", + "position": 3, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_silences", + "name": "starts_at", + "position": 4, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_silences", + "name": "ends_at", + "position": 5, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_silences", + "name": "maintenance_window_id", + "position": 6, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_silences", + "name": "exclude_from_baselines", + "position": 7, + "type": "boolean", + "notNull": true, + "default": "false", + "identity": null + }, + { + "kind": "column", + "table": "alert_silences", + "name": "created_at", + "position": 8, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_silences", + "name": "updated_at", + "position": 9, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_silences", + "name": "created_by", + "position": 10, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "alert_silences", + "name": "updated_by", + "position": 11, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "anomaly_detector_settings", + "name": "org_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "anomaly_detector_settings", + "name": "enabled", + "position": 1, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "anomaly_detector_settings", + "name": "sensitivity", + "position": 2, + "type": "text", + "notNull": true, + "default": "'normal'", + "identity": null + }, + { + "kind": "column", + "table": "anomaly_detector_settings", + "name": "muted_signals_json", + "position": 3, + "type": "jsonb", + "notNull": true, + "default": "'[]'", + "identity": null + }, + { + "kind": "column", + "table": "anomaly_detector_settings", + "name": "included_environments_json", + "position": 4, + "type": "jsonb", + "notNull": true, + "default": "'[]'", + "identity": null + }, + { + "kind": "column", + "table": "anomaly_detector_settings", + "name": "last_tick_at", + "position": 5, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "anomaly_detector_settings", + "name": "created_at", + "position": 6, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "anomaly_detector_settings", + "name": "updated_at", + "position": 7, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "anomaly_detector_settings", + "name": "updated_by", + "position": 8, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "anomaly_detector_states", + "name": "org_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "anomaly_detector_states", + "name": "detector_key", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "anomaly_detector_states", + "name": "signal_type", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "anomaly_detector_states", + "name": "service_name", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "anomaly_detector_states", + "name": "deployment_env", + "position": 4, + "type": "text", + "notNull": true, + "default": "''", + "identity": null + }, + { + "kind": "column", + "table": "anomaly_detector_states", + "name": "fingerprint_hash", + "position": 5, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "anomaly_detector_states", + "name": "consecutive_breaches", + "position": 6, + "type": "integer", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "anomaly_detector_states", + "name": "consecutive_healthy", + "position": 7, + "type": "integer", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "anomaly_detector_states", + "name": "last_status", + "position": 8, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "anomaly_detector_states", + "name": "last_value", + "position": 9, + "type": "double precision", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "anomaly_detector_states", + "name": "baseline_median", + "position": 10, + "type": "double precision", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "anomaly_detector_states", + "name": "last_sample_count", + "position": 11, + "type": "integer", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "anomaly_detector_states", + "name": "last_evaluated_at", + "position": 12, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "anomaly_detector_states", + "name": "open_incident_id", + "position": 13, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "anomaly_detector_states", + "name": "last_resolved_at", + "position": 14, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "anomaly_detector_states", + "name": "last_incident_id", + "position": 15, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "anomaly_detector_states", + "name": "updated_at", + "position": 16, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "anomaly_incidents", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "anomaly_incidents", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "anomaly_incidents", + "name": "detector_key", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "anomaly_incidents", + "name": "signal_type", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "anomaly_incidents", + "name": "service_name", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "anomaly_incidents", + "name": "deployment_env", + "position": 5, + "type": "text", + "notNull": true, + "default": "''", + "identity": null + }, + { + "kind": "column", + "table": "anomaly_incidents", + "name": "fingerprint_hash", + "position": 6, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "anomaly_incidents", + "name": "error_issue_id", + "position": 7, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "anomaly_incidents", + "name": "status", + "position": 8, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "anomaly_incidents", + "name": "severity", + "position": 9, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "anomaly_incidents", + "name": "opened_value", + "position": 10, + "type": "double precision", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "anomaly_incidents", + "name": "baseline_median", + "position": 11, + "type": "double precision", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "anomaly_incidents", + "name": "baseline_sigma", + "position": 12, + "type": "double precision", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "anomaly_incidents", + "name": "threshold_value", + "position": 13, + "type": "double precision", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "anomaly_incidents", + "name": "last_observed_value", + "position": 14, + "type": "double precision", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "anomaly_incidents", + "name": "last_sample_count", + "position": 15, + "type": "integer", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "anomaly_incidents", + "name": "first_triggered_at", + "position": 16, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "anomaly_incidents", + "name": "last_triggered_at", + "position": 17, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "anomaly_incidents", + "name": "resolved_at", + "position": 18, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "anomaly_incidents", + "name": "resolve_reason", + "position": 19, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "anomaly_incidents", + "name": "triage_status", + "position": 20, + "type": "text", + "notNull": true, + "default": "'none'", + "identity": null + }, + { + "kind": "column", + "table": "anomaly_incidents", + "name": "dedupe_key", + "position": 21, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "anomaly_incidents", + "name": "fingerprints_json", + "position": 22, + "type": "jsonb", + "notNull": true, + "default": "'[]'", + "identity": null + }, + { + "kind": "column", + "table": "anomaly_incidents", + "name": "reopen_count", + "position": 23, + "type": "integer", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "anomaly_incidents", + "name": "last_reopened_at", + "position": 24, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "anomaly_incidents", + "name": "created_at", + "position": 25, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "anomaly_incidents", + "name": "updated_at", + "position": 26, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "api_keys", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "api_keys", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "api_keys", + "name": "name", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "api_keys", + "name": "description", + "position": 3, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "api_keys", + "name": "key_hash", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "api_keys", + "name": "key_prefix", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "api_keys", + "name": "revoked", + "position": 6, + "type": "boolean", + "notNull": true, + "default": "false", + "identity": null + }, + { + "kind": "column", + "table": "api_keys", + "name": "revoked_at", + "position": 7, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "api_keys", + "name": "last_used_at", + "position": 8, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "api_keys", + "name": "expires_at", + "position": 9, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "api_keys", + "name": "metadata_json", + "position": 10, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "api_keys", + "name": "scopes", + "position": 11, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "api_keys", + "name": "kind", + "position": 12, + "type": "text", + "notNull": true, + "default": "'standard'", + "identity": null + }, + { + "kind": "column", + "table": "api_keys", + "name": "created_at", + "position": 13, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "api_keys", + "name": "created_by", + "position": 14, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "api_keys", + "name": "created_by_email", + "position": 15, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "aws_connections", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "aws_connections", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "aws_connections", + "name": "source_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "aws_connections", + "name": "account_id", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "aws_connections", + "name": "modules", + "position": 4, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "aws_connections", + "name": "granted_modules", + "position": 5, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "aws_connections", + "name": "template_version", + "position": 6, + "type": "integer", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "aws_connections", + "name": "verified_at", + "position": 7, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "aws_connections", + "name": "last_checked_at", + "position": 8, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "aws_connections", + "name": "last_check_error", + "position": 9, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "aws_connections", + "name": "check_lease_until", + "position": 10, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "aws_connections", + "name": "metric_stream", + "position": 11, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "aws_connections", + "name": "metric_stream_changed_at", + "position": 12, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "aws_connections", + "name": "stream_secret_ciphertext", + "position": 13, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "aws_connections", + "name": "stream_secret_iv", + "position": 14, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "aws_connections", + "name": "stream_secret_tag", + "position": 15, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "aws_connections", + "name": "stream_secret_hash", + "position": 16, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "aws_connections", + "name": "stream_last_received_at", + "position": 17, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "aws_connections", + "name": "stream_last_error", + "position": 18, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "aws_connections", + "name": "events_key_salt", + "position": 19, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "aws_connections", + "name": "created_by", + "position": 20, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "aws_connections", + "name": "created_at", + "position": 21, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "aws_connections", + "name": "updated_at", + "position": 22, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cancellation_reviews", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cancellation_reviews", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cancellation_reviews", + "name": "plan_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cancellation_reviews", + "name": "subscription_started_at", + "position": 3, + "type": "bigint", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cancellation_reviews", + "name": "canceled_at", + "position": 4, + "type": "bigint", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cancellation_reviews", + "name": "snapshot_json", + "position": 5, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cancellation_reviews", + "name": "rule_reason", + "position": 6, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cancellation_reviews", + "name": "model_read", + "position": 7, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cancellation_reviews", + "name": "posted_at", + "position": 8, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cancellation_reviews", + "name": "created_at", + "position": 9, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cancellation_reviews", + "name": "updated_at", + "position": 10, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "chat_identities", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "chat_identities", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "chat_identities", + "name": "connector", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "chat_identities", + "name": "external_user_id", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "chat_identities", + "name": "user_id", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "chat_identities", + "name": "display_name", + "position": 5, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "chat_identities", + "name": "created_at", + "position": 6, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "chat_workspaces", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "chat_workspaces", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "chat_workspaces", + "name": "connector", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "chat_workspaces", + "name": "external_workspace_id", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "chat_workspaces", + "name": "name", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "chat_workspaces", + "name": "settings", + "position": 5, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "chat_workspaces", + "name": "credentials_ciphertext", + "position": 6, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "chat_workspaces", + "name": "credentials_iv", + "position": 7, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "chat_workspaces", + "name": "credentials_tag", + "position": 8, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "chat_workspaces", + "name": "alerts_enabled", + "position": 9, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "chat_workspaces", + "name": "direct_messages_enabled", + "position": 10, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "chat_workspaces", + "name": "assistant_enabled", + "position": 11, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "chat_workspaces", + "name": "created_at", + "position": 12, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cli_device_authorizations", + "name": "device_code_hash", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cli_device_authorizations", + "name": "user_code_hash", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cli_device_authorizations", + "name": "device_name", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cli_device_authorizations", + "name": "approved_org_id", + "position": 3, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cli_device_authorizations", + "name": "approved_user_id", + "position": 4, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cli_device_authorizations", + "name": "approved_roles", + "position": 5, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cli_device_authorizations", + "name": "approved_user_email", + "position": 6, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cli_device_authorizations", + "name": "api_key_id", + "position": 7, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cli_device_authorizations", + "name": "token_ciphertext", + "position": 8, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cli_device_authorizations", + "name": "token_iv", + "position": 9, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cli_device_authorizations", + "name": "token_tag", + "position": 10, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cli_device_authorizations", + "name": "approved_at", + "position": 11, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cli_device_authorizations", + "name": "denied_at", + "position": 12, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cli_device_authorizations", + "name": "created_at", + "position": 13, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cli_device_authorizations", + "name": "expires_at", + "position": 14, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloud_security_findings", + "name": "org_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloud_security_findings", + "name": "connection_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloud_security_findings", + "name": "account_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloud_security_findings", + "name": "region", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloud_security_findings", + "name": "source", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloud_security_findings", + "name": "finding_id", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloud_security_findings", + "name": "type", + "position": 6, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloud_security_findings", + "name": "title", + "position": 7, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloud_security_findings", + "name": "description", + "position": 8, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloud_security_findings", + "name": "severity", + "position": 9, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloud_security_findings", + "name": "status", + "position": 10, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloud_security_findings", + "name": "resource_type", + "position": 11, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloud_security_findings", + "name": "resource_id", + "position": 12, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloud_security_findings", + "name": "resource_name", + "position": 13, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloud_security_findings", + "name": "occurrences", + "position": 14, + "type": "integer", + "notNull": true, + "default": "1", + "identity": null + }, + { + "kind": "column", + "table": "cloud_security_findings", + "name": "first_seen_at", + "position": 15, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloud_security_findings", + "name": "last_seen_at", + "position": 16, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloud_security_findings", + "name": "provider_updated_at", + "position": 17, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloud_security_findings", + "name": "closed_at", + "position": 18, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloud_security_findings", + "name": "detail", + "position": 19, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloud_security_findings", + "name": "synced_at", + "position": 20, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloud_security_service_states", + "name": "org_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloud_security_service_states", + "name": "connection_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloud_security_service_states", + "name": "region", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloud_security_service_states", + "name": "source", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloud_security_service_states", + "name": "state", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloud_security_service_states", + "name": "cursor_at", + "position": 5, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloud_security_service_states", + "name": "window_ms", + "position": 6, + "type": "bigint", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloud_security_service_states", + "name": "last_error", + "position": 7, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloud_security_service_states", + "name": "checked_at", + "position": 8, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloud_security_service_states", + "name": "pushed_at", + "position": 9, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_analytics_state", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_analytics_state", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_analytics_state", + "name": "account_id", + "position": 2, + "type": "text", + "notNull": true, + "default": "''", + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_analytics_state", + "name": "dataset", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_analytics_state", + "name": "zone_id", + "position": 4, + "type": "text", + "notNull": true, + "default": "''", + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_analytics_state", + "name": "zone_name", + "position": 5, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_analytics_state", + "name": "enabled", + "position": 6, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_analytics_state", + "name": "watermark_at", + "position": 7, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_analytics_state", + "name": "backfill_at", + "position": 8, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_analytics_state", + "name": "settings_json", + "position": 9, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_analytics_state", + "name": "settings_fetched_at", + "position": 10, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_analytics_state", + "name": "quantiles_available", + "position": 11, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_analytics_state", + "name": "discovered_at", + "position": 12, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_analytics_state", + "name": "live_scripts_json", + "position": 13, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_analytics_state", + "name": "grant_call_cap", + "position": 14, + "type": "integer", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_analytics_state", + "name": "last_success_at", + "position": 15, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_analytics_state", + "name": "last_error", + "position": 16, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_analytics_state", + "name": "last_error_at", + "position": 17, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_analytics_state", + "name": "lease_until", + "position": 18, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_analytics_state", + "name": "backoff_until", + "position": 19, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_analytics_state", + "name": "backoff_streak", + "position": 20, + "type": "integer", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_analytics_state", + "name": "backoff_reason", + "position": 21, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_analytics_state", + "name": "created_at", + "position": 22, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_analytics_state", + "name": "updated_at", + "position": 23, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_feature_settings", + "name": "org_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_feature_settings", + "name": "http_traffic_enabled", + "position": 1, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_feature_settings", + "name": "firewall_enabled", + "position": 2, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_feature_settings", + "name": "dns_enabled", + "position": 3, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_feature_settings", + "name": "workers_enabled", + "position": 4, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_feature_settings", + "name": "queues_enabled", + "position": 5, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_feature_settings", + "name": "durable_objects_enabled", + "position": 6, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_feature_settings", + "name": "created_at", + "position": 7, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_feature_settings", + "name": "updated_at", + "position": 8, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_feature_settings", + "name": "updated_by", + "position": 9, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_hyperdrive_configs", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_hyperdrive_configs", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_hyperdrive_configs", + "name": "account_id", + "position": 2, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_hyperdrive_configs", + "name": "config_id", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_hyperdrive_configs", + "name": "name", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_hyperdrive_configs", + "name": "origin_host", + "position": 5, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_hyperdrive_configs", + "name": "origin_port", + "position": 6, + "type": "integer", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_hyperdrive_configs", + "name": "origin_scheme", + "position": 7, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_hyperdrive_configs", + "name": "origin_database", + "position": 8, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_hyperdrive_configs", + "name": "origin_user", + "position": 9, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_hyperdrive_configs", + "name": "deleted_at", + "position": 10, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_hyperdrive_configs", + "name": "created_at", + "position": 11, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_hyperdrive_configs", + "name": "updated_at", + "position": 12, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_logpush_connectors", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_logpush_connectors", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_logpush_connectors", + "name": "source_id", + "position": 2, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_logpush_connectors", + "name": "name", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_logpush_connectors", + "name": "zone_name", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_logpush_connectors", + "name": "service_name", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_logpush_connectors", + "name": "dataset", + "position": 6, + "type": "text", + "notNull": true, + "default": "'http_requests'", + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_logpush_connectors", + "name": "secret_ciphertext", + "position": 7, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_logpush_connectors", + "name": "secret_iv", + "position": 8, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_logpush_connectors", + "name": "secret_tag", + "position": 9, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_logpush_connectors", + "name": "secret_hash", + "position": 10, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_logpush_connectors", + "name": "enabled", + "position": 11, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_logpush_connectors", + "name": "last_received_at", + "position": 12, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_logpush_connectors", + "name": "last_error", + "position": 13, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_logpush_connectors", + "name": "secret_rotated_at", + "position": 14, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_logpush_connectors", + "name": "created_at", + "position": 15, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_logpush_connectors", + "name": "updated_at", + "position": 16, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_logpush_connectors", + "name": "created_by", + "position": 17, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_logpush_connectors", + "name": "updated_by", + "position": 18, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_zone_settings", + "name": "org_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_zone_settings", + "name": "account_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_zone_settings", + "name": "watch_new_zones", + "position": 2, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_zone_settings", + "name": "zone_overrides", + "position": 3, + "type": "jsonb", + "notNull": true, + "default": "'{}'", + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_zone_settings", + "name": "created_at", + "position": 4, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_zone_settings", + "name": "updated_at", + "position": 5, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cloudflare_zone_settings", + "name": "updated_by", + "position": 6, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cookieless_salts", + "name": "day", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cookieless_salts", + "name": "salt", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cookieless_salts", + "name": "created_at", + "position": 2, + "type": "timestamp with time zone", + "notNull": true, + "default": "now()", + "identity": null + }, + { + "kind": "column", + "table": "cookieless_visits", + "name": "org_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cookieless_visits", + "name": "visitor_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cookieless_visits", + "name": "visit_token", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cookieless_visits", + "name": "last_seen_at", + "position": 3, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cost_connections", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cost_connections", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cost_connections", + "name": "provider", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cost_connections", + "name": "secret_ciphertext", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cost_connections", + "name": "secret_iv", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cost_connections", + "name": "secret_tag", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cost_connections", + "name": "account_id", + "position": 6, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cost_connections", + "name": "account_label", + "position": 7, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cost_connections", + "name": "created_at", + "position": 8, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cost_connections", + "name": "updated_at", + "position": 9, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cost_connections", + "name": "updated_by", + "position": 10, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cost_sources", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cost_sources", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cost_sources", + "name": "provider", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cost_sources", + "name": "connection_ref", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cost_sources", + "name": "account_id", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cost_sources", + "name": "enabled", + "position": 5, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "cost_sources", + "name": "watermark_date", + "position": 6, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cost_sources", + "name": "backfill_date", + "position": 7, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cost_sources", + "name": "last_synced_at", + "position": 8, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cost_sources", + "name": "last_settled_at", + "position": 9, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cost_sources", + "name": "last_error", + "position": 10, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cost_sources", + "name": "last_error_reason", + "position": 11, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cost_sources", + "name": "lease_until", + "position": 12, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cost_sources", + "name": "next_attempt_at", + "position": 13, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cost_sources", + "name": "consecutive_failures", + "position": 14, + "type": "integer", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "cost_sources", + "name": "requests_month", + "position": 15, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cost_sources", + "name": "requests_count", + "position": 16, + "type": "integer", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "cost_sources", + "name": "created_at", + "position": 17, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "cost_sources", + "name": "updated_at", + "position": 18, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dashboard_shares", + "name": "org_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dashboard_shares", + "name": "id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dashboard_shares", + "name": "dashboard_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dashboard_shares", + "name": "widget_id", + "position": 3, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dashboard_shares", + "name": "mode", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dashboard_shares", + "name": "token_hash", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dashboard_shares", + "name": "token_ciphertext", + "position": 6, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dashboard_shares", + "name": "token_iv", + "position": 7, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dashboard_shares", + "name": "token_tag", + "position": 8, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dashboard_shares", + "name": "token_suffix", + "position": 9, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dashboard_shares", + "name": "created_at", + "position": 10, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dashboard_shares", + "name": "created_by", + "position": 11, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dashboard_shares", + "name": "updated_at", + "position": 12, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dashboard_shares", + "name": "updated_by", + "position": 13, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dashboard_shares", + "name": "revoked_at", + "position": 14, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dashboard_shares", + "name": "expires_at", + "position": 15, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dashboard_versions", + "name": "org_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dashboard_versions", + "name": "id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dashboard_versions", + "name": "dashboard_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dashboard_versions", + "name": "version_number", + "position": 3, + "type": "integer", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dashboard_versions", + "name": "snapshot_json", + "position": 4, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dashboard_versions", + "name": "change_kind", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dashboard_versions", + "name": "change_summary", + "position": 6, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dashboard_versions", + "name": "source_version_id", + "position": 7, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dashboard_versions", + "name": "created_at", + "position": 8, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dashboard_versions", + "name": "created_by", + "position": 9, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dashboards", + "name": "org_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dashboards", + "name": "id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dashboards", + "name": "name", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dashboards", + "name": "payload_json", + "position": 3, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dashboards", + "name": "created_at", + "position": 4, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dashboards", + "name": "updated_at", + "position": 5, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dashboards", + "name": "created_by", + "position": 6, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dashboards", + "name": "updated_by", + "position": 7, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dashboards", + "name": "version", + "position": 8, + "type": "integer", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "dependency_findings", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_findings", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_findings", + "name": "repository_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_findings", + "name": "lockfile_path", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_findings", + "name": "ecosystem", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_findings", + "name": "package_name", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_findings", + "name": "advisory_id", + "position": 6, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_findings", + "name": "aliases", + "position": 7, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_findings", + "name": "severity", + "position": 8, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_findings", + "name": "summary", + "position": 9, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_findings", + "name": "versions", + "position": 10, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_findings", + "name": "fixed_in", + "position": 11, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_findings", + "name": "relation", + "position": 12, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_findings", + "name": "status", + "position": 13, + "type": "text", + "notNull": true, + "default": "'open'", + "identity": null + }, + { + "kind": "column", + "table": "dependency_findings", + "name": "first_seen_scan_id", + "position": 14, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_findings", + "name": "last_seen_scan_id", + "position": 15, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_findings", + "name": "first_seen_sha", + "position": 16, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_findings", + "name": "last_seen_sha", + "position": 17, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_findings", + "name": "fixed_scan_id", + "position": 18, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_findings", + "name": "fixed_sha", + "position": 19, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_findings", + "name": "status_reason", + "position": 20, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_findings", + "name": "status_changed_by", + "position": 21, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_findings", + "name": "status_changed_at", + "position": 22, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_findings", + "name": "created_at", + "position": 23, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_findings", + "name": "updated_at", + "position": 24, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_scan_matches", + "name": "scan_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_scan_matches", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_scan_matches", + "name": "lockfile_path", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_scan_matches", + "name": "ecosystem", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_scan_matches", + "name": "package_name", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_scan_matches", + "name": "version", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_scan_matches", + "name": "relation", + "position": 6, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_scan_matches", + "name": "advisory_id", + "position": 7, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_scan_matches", + "name": "aliases", + "position": 8, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_scan_matches", + "name": "severity", + "position": 9, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_scan_matches", + "name": "summary", + "position": 10, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_scan_matches", + "name": "fixed_in", + "position": 11, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_scans", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_scans", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_scans", + "name": "repository_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_scans", + "name": "commit_sha", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_scans", + "name": "ref", + "position": 4, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_scans", + "name": "trigger", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_scans", + "name": "default_branch_head", + "position": 6, + "type": "boolean", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_scans", + "name": "status", + "position": 7, + "type": "text", + "notNull": true, + "default": "'running'", + "identity": null + }, + { + "kind": "column", + "table": "dependency_scans", + "name": "lockfiles", + "position": 8, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_scans", + "name": "package_count", + "position": 9, + "type": "integer", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "dependency_scans", + "name": "vulnerable_count", + "position": 10, + "type": "integer", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "dependency_scans", + "name": "error", + "position": 11, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_scans", + "name": "advisory_fingerprint", + "position": 12, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_scans", + "name": "started_at", + "position": 13, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "dependency_scans", + "name": "finished_at", + "position": 14, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_credentials", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_credentials", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_credentials", + "name": "user_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_credentials", + "name": "installation_id", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_credentials", + "name": "public_jwk", + "position": 4, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_credentials", + "name": "jkt", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_credentials", + "name": "roles", + "position": 6, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_credentials", + "name": "scopes", + "position": 7, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_credentials", + "name": "attested", + "position": 8, + "type": "boolean", + "notNull": true, + "default": "false", + "identity": null + }, + { + "kind": "column", + "table": "device_credentials", + "name": "attestation", + "position": 9, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_credentials", + "name": "created_at", + "position": 10, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_credentials", + "name": "last_used_at", + "position": 11, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_credentials", + "name": "expires_at", + "position": 12, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_credentials", + "name": "hard_expires_at", + "position": 13, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_credentials", + "name": "revoked_at", + "position": 14, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_policy_findings", + "name": "org_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_policy_findings", + "name": "source", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_policy_findings", + "name": "connection_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_policy_findings", + "name": "policy_id", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_policy_findings", + "name": "name", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_policy_findings", + "name": "group_name", + "position": 5, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_policy_findings", + "name": "description", + "position": 6, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_policy_findings", + "name": "resolution", + "position": 7, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_policy_findings", + "name": "critical", + "position": 8, + "type": "boolean", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_policy_findings", + "name": "platform", + "position": 9, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_policy_findings", + "name": "failing_device_count", + "position": 10, + "type": "integer", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_policy_findings", + "name": "passing_device_count", + "position": 11, + "type": "integer", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_policy_findings", + "name": "failing_devices", + "position": 12, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_policy_findings", + "name": "counted_at", + "position": 13, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_policy_findings", + "name": "url", + "position": 14, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_policy_findings", + "name": "first_seen_at", + "position": 15, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_policy_findings", + "name": "last_seen_at", + "position": 16, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_proof_replays", + "name": "key", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_proof_replays", + "name": "expires_at", + "position": 1, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_vulnerability_findings", + "name": "org_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_vulnerability_findings", + "name": "source", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_vulnerability_findings", + "name": "connection_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_vulnerability_findings", + "name": "cve", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_vulnerability_findings", + "name": "cvss_score", + "position": 4, + "type": "double precision", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_vulnerability_findings", + "name": "epss_probability", + "position": 5, + "type": "double precision", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_vulnerability_findings", + "name": "known_exploited", + "position": 6, + "type": "boolean", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_vulnerability_findings", + "name": "details_link", + "position": 7, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_vulnerability_findings", + "name": "device_count", + "position": 8, + "type": "integer", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_vulnerability_findings", + "name": "software", + "position": 9, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_vulnerability_findings", + "name": "url", + "position": 10, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_vulnerability_findings", + "name": "first_seen_at", + "position": 11, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "device_vulnerability_findings", + "name": "last_seen_at", + "position": 12, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "digest_subscriptions", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "digest_subscriptions", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "digest_subscriptions", + "name": "user_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "digest_subscriptions", + "name": "email", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "digest_subscriptions", + "name": "enabled", + "position": 4, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "digest_subscriptions", + "name": "opted_out_at", + "position": 5, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "digest_subscriptions", + "name": "day_of_week", + "position": 6, + "type": "integer", + "notNull": true, + "default": "1", + "identity": null + }, + { + "kind": "column", + "table": "digest_subscriptions", + "name": "timezone", + "position": 7, + "type": "text", + "notNull": true, + "default": "'UTC'", + "identity": null + }, + { + "kind": "column", + "table": "digest_subscriptions", + "name": "send_hour", + "position": 8, + "type": "integer", + "notNull": true, + "default": "9", + "identity": null + }, + { + "kind": "column", + "table": "digest_subscriptions", + "name": "namespaces_json", + "position": 9, + "type": "text", + "notNull": true, + "default": "'[]'", + "identity": null + }, + { + "kind": "column", + "table": "digest_subscriptions", + "name": "environments_json", + "position": 10, + "type": "text", + "notNull": true, + "default": "'[]'", + "identity": null + }, + { + "kind": "column", + "table": "digest_subscriptions", + "name": "last_sent_at", + "position": 11, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "digest_subscriptions", + "name": "last_attempted_at", + "position": 12, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "digest_subscriptions", + "name": "web_analytics_enabled", + "position": 13, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "digest_subscriptions", + "name": "web_analytics_opted_out_at", + "position": 14, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "digest_subscriptions", + "name": "web_analytics_last_sent_at", + "position": 15, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "digest_subscriptions", + "name": "web_analytics_last_attempted_at", + "position": 16, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "digest_subscriptions", + "name": "created_at", + "position": 17, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "digest_subscriptions", + "name": "updated_at", + "position": 18, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_fingerprint_candidates", + "name": "org_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_fingerprint_candidates", + "name": "fingerprint_hash", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_fingerprint_candidates", + "name": "service_name", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_fingerprint_candidates", + "name": "exception_type", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_fingerprint_candidates", + "name": "exception_message", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_fingerprint_candidates", + "name": "error_label", + "position": 5, + "type": "text", + "notNull": true, + "default": "''", + "identity": null + }, + { + "kind": "column", + "table": "error_fingerprint_candidates", + "name": "top_frame", + "position": 6, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_fingerprint_candidates", + "name": "service_versions_json", + "position": 7, + "type": "jsonb", + "notNull": true, + "default": "'[]'", + "identity": null + }, + { + "kind": "column", + "table": "error_fingerprint_candidates", + "name": "occurrence_count", + "position": 8, + "type": "integer", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "error_fingerprint_candidates", + "name": "first_seen_at", + "position": 9, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_fingerprint_candidates", + "name": "last_seen_at", + "position": 10, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_fingerprint_candidates", + "name": "updated_at", + "position": 11, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_grouping_configs", + "name": "org_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_grouping_configs", + "name": "rules_json", + "position": 1, + "type": "jsonb", + "notNull": true, + "default": "'[]'", + "identity": null + }, + { + "kind": "column", + "table": "error_grouping_configs", + "name": "updated_at", + "position": 2, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_grouping_configs", + "name": "updated_by", + "position": 3, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_grouping_keys", + "name": "org_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_grouping_keys", + "name": "fingerprint_hash", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_grouping_keys", + "name": "grouping_key", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_grouping_keys", + "name": "key_version", + "position": 3, + "type": "integer", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_grouping_keys", + "name": "config_digest", + "position": 4, + "type": "text", + "notNull": true, + "default": "''", + "identity": null + }, + { + "kind": "column", + "table": "error_grouping_keys", + "name": "rule", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_grouping_keys", + "name": "pinned", + "position": 6, + "type": "boolean", + "notNull": true, + "default": "false", + "identity": null + }, + { + "kind": "column", + "table": "error_grouping_keys", + "name": "created_at", + "position": 7, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_grouping_keys", + "name": "updated_at", + "position": 8, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_incidents", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_incidents", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_incidents", + "name": "issue_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_incidents", + "name": "status", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_incidents", + "name": "reason", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_incidents", + "name": "first_triggered_at", + "position": 5, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_incidents", + "name": "last_triggered_at", + "position": 6, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_incidents", + "name": "resolved_at", + "position": 7, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_incidents", + "name": "occurrence_count", + "position": 8, + "type": "integer", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "error_incidents", + "name": "created_at", + "position": 9, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_incidents", + "name": "updated_at", + "position": 10, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_events", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_events", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_events", + "name": "issue_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_events", + "name": "actor_id", + "position": 3, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_events", + "name": "type", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_events", + "name": "from_state", + "position": 5, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_events", + "name": "to_state", + "position": 6, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_events", + "name": "payload_json", + "position": 7, + "type": "jsonb", + "notNull": true, + "default": "'{}'", + "identity": null + }, + { + "kind": "column", + "table": "error_issue_events", + "name": "created_at", + "position": 8, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_fingerprints", + "name": "org_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_fingerprints", + "name": "fingerprint_hash", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_fingerprints", + "name": "issue_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_fingerprints", + "name": "source", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_fingerprints", + "name": "origin_issue_id", + "position": 4, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_fingerprints", + "name": "created_at", + "position": 5, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_pull_requests", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_pull_requests", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_pull_requests", + "name": "issue_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_pull_requests", + "name": "provider", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_pull_requests", + "name": "external_repo_id", + "position": 4, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_pull_requests", + "name": "repo_full_name", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_pull_requests", + "name": "number", + "position": 6, + "type": "integer", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_pull_requests", + "name": "url", + "position": 7, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_pull_requests", + "name": "title", + "position": 8, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_pull_requests", + "name": "author_login", + "position": 9, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_pull_requests", + "name": "state", + "position": 10, + "type": "text", + "notNull": true, + "default": "'open'", + "identity": null + }, + { + "kind": "column", + "table": "error_issue_pull_requests", + "name": "merged_at", + "position": 11, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_pull_requests", + "name": "merge_commit_sha", + "position": 12, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_pull_requests", + "name": "link_source", + "position": 13, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_pull_requests", + "name": "linked_by_actor_id", + "position": 14, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_pull_requests", + "name": "created_at", + "position": 15, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_pull_requests", + "name": "updated_at", + "position": 16, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_states", + "name": "org_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_states", + "name": "issue_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_states", + "name": "last_observed_occurrence_at", + "position": 2, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_states", + "name": "last_evaluated_at", + "position": 3, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_states", + "name": "open_incident_id", + "position": 4, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_states", + "name": "updated_at", + "position": 5, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_verifications", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_verifications", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_verifications", + "name": "issue_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_verifications", + "name": "pull_request_id", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_verifications", + "name": "status", + "position": 4, + "type": "text", + "notNull": true, + "default": "'waiting'", + "identity": null + }, + { + "kind": "column", + "table": "error_issue_verifications", + "name": "merged_at", + "position": 5, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_verifications", + "name": "verify_after", + "position": 6, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_verifications", + "name": "baseline_versions_json", + "position": 7, + "type": "jsonb", + "notNull": true, + "default": "'[]'", + "identity": null + }, + { + "kind": "column", + "table": "error_issue_verifications", + "name": "baseline_occurrence_count", + "position": 8, + "type": "integer", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "error_issue_verifications", + "name": "baseline_rate_per_hour", + "position": 9, + "type": "double precision", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "error_issue_verifications", + "name": "investigation_id", + "position": 10, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_verifications", + "name": "verdict", + "position": 11, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_verifications", + "name": "verdict_note", + "position": 12, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_verifications", + "name": "post_merge_occurrence_count", + "position": 13, + "type": "integer", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "error_issue_verifications", + "name": "attempt", + "position": 14, + "type": "integer", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "error_issue_verifications", + "name": "created_at", + "position": 15, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issue_verifications", + "name": "updated_at", + "position": 16, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issues", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issues", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issues", + "name": "kind", + "position": 2, + "type": "text", + "notNull": true, + "default": "'error'", + "identity": null + }, + { + "kind": "column", + "table": "error_issues", + "name": "source_ref_json", + "position": 3, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issues", + "name": "fingerprint_hash", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issues", + "name": "fingerprint_version", + "position": 5, + "type": "integer", + "notNull": true, + "default": "1", + "identity": null + }, + { + "kind": "column", + "table": "error_issues", + "name": "service_name", + "position": 6, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issues", + "name": "exception_type", + "position": 7, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issues", + "name": "exception_message", + "position": 8, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issues", + "name": "error_label", + "position": 9, + "type": "text", + "notNull": true, + "default": "''", + "identity": null + }, + { + "kind": "column", + "table": "error_issues", + "name": "top_frame", + "position": 10, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issues", + "name": "workflow_state", + "position": 11, + "type": "text", + "notNull": true, + "default": "'triage'", + "identity": null + }, + { + "kind": "column", + "table": "error_issues", + "name": "priority", + "position": 12, + "type": "integer", + "notNull": true, + "default": "3", + "identity": null + }, + { + "kind": "column", + "table": "error_issues", + "name": "severity", + "position": 13, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issues", + "name": "severity_source", + "position": 14, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issues", + "name": "assigned_actor_id", + "position": 15, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issues", + "name": "lease_holder_actor_id", + "position": 16, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issues", + "name": "lease_expires_at", + "position": 17, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issues", + "name": "claimed_at", + "position": 18, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issues", + "name": "notes", + "position": 19, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issues", + "name": "first_seen_at", + "position": 20, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issues", + "name": "last_seen_at", + "position": 21, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issues", + "name": "occurrence_count", + "position": 22, + "type": "integer", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "error_issues", + "name": "resolved_at", + "position": 23, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issues", + "name": "resolved_by_actor_id", + "position": 24, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issues", + "name": "last_resolved_at", + "position": 25, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issues", + "name": "last_regressed_at", + "position": 26, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issues", + "name": "regression_count", + "position": 27, + "type": "integer", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "error_issues", + "name": "seen_versions_json", + "position": 28, + "type": "jsonb", + "notNull": true, + "default": "'[]'", + "identity": null + }, + { + "kind": "column", + "table": "error_issues", + "name": "resolved_versions_json", + "position": 29, + "type": "jsonb", + "notNull": true, + "default": "'[]'", + "identity": null + }, + { + "kind": "column", + "table": "error_issues", + "name": "snooze_until", + "position": 30, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issues", + "name": "archived_at", + "position": 31, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issues", + "name": "merged_into_issue_id", + "position": 32, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issues", + "name": "created_at", + "position": 33, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_issues", + "name": "updated_at", + "position": 34, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_notification_deliveries", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_notification_deliveries", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_notification_deliveries", + "name": "destination_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_notification_deliveries", + "name": "delivery_key", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_notification_deliveries", + "name": "payload_json", + "position": 4, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_notification_deliveries", + "name": "status", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_notification_deliveries", + "name": "attempt_count", + "position": 6, + "type": "integer", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "error_notification_deliveries", + "name": "scheduled_at", + "position": 7, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_notification_deliveries", + "name": "claimed_at", + "position": 8, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_notification_deliveries", + "name": "claim_expires_at", + "position": 9, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_notification_deliveries", + "name": "claimed_by", + "position": 10, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_notification_deliveries", + "name": "attempted_at", + "position": 11, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_notification_deliveries", + "name": "error_message", + "position": 12, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_notification_deliveries", + "name": "created_at", + "position": 13, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_notification_deliveries", + "name": "updated_at", + "position": 14, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_notification_policies", + "name": "org_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_notification_policies", + "name": "enabled", + "position": 1, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "error_notification_policies", + "name": "destination_ids_json", + "position": 2, + "type": "jsonb", + "notNull": true, + "default": "'[]'", + "identity": null + }, + { + "kind": "column", + "table": "error_notification_policies", + "name": "notify_on_first_seen", + "position": 3, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "error_notification_policies", + "name": "notify_on_regression", + "position": 4, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "error_notification_policies", + "name": "notify_on_resolve", + "position": 5, + "type": "boolean", + "notNull": true, + "default": "false", + "identity": null + }, + { + "kind": "column", + "table": "error_notification_policies", + "name": "notify_on_transition_in_review", + "position": 6, + "type": "boolean", + "notNull": true, + "default": "false", + "identity": null + }, + { + "kind": "column", + "table": "error_notification_policies", + "name": "notify_on_transition_done", + "position": 7, + "type": "boolean", + "notNull": true, + "default": "false", + "identity": null + }, + { + "kind": "column", + "table": "error_notification_policies", + "name": "notify_on_claim", + "position": 8, + "type": "boolean", + "notNull": true, + "default": "false", + "identity": null + }, + { + "kind": "column", + "table": "error_notification_policies", + "name": "min_occurrence_count", + "position": 9, + "type": "integer", + "notNull": true, + "default": "1", + "identity": null + }, + { + "kind": "column", + "table": "error_notification_policies", + "name": "severity", + "position": 10, + "type": "text", + "notNull": true, + "default": "'warning'", + "identity": null + }, + { + "kind": "column", + "table": "error_notification_policies", + "name": "updated_at", + "position": 11, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_notification_policies", + "name": "updated_by", + "position": 12, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_tick_states", + "name": "org_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_tick_states", + "name": "processed_through", + "position": 1, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_tick_states", + "name": "bootstrap_completed", + "position": 2, + "type": "boolean", + "notNull": true, + "default": "false", + "identity": null + }, + { + "kind": "column", + "table": "error_tick_states", + "name": "claim_token", + "position": 3, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_tick_states", + "name": "claim_expires_at", + "position": 4, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "error_tick_states", + "name": "updated_at", + "position": 5, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "escalation_chains", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "escalation_chains", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "escalation_chains", + "name": "name", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "escalation_chains", + "name": "description", + "position": 3, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "escalation_chains", + "name": "steps_json", + "position": 4, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "escalation_chains", + "name": "repeat_count", + "position": 5, + "type": "integer", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "escalation_chains", + "name": "created_at", + "position": 6, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "escalation_chains", + "name": "updated_at", + "position": 7, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "escalation_chains", + "name": "created_by", + "position": 8, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "escalation_chains", + "name": "updated_by", + "position": 9, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "external_data_source_catalog_entries", + "name": "source_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "external_data_source_catalog_entries", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "external_data_source_catalog_entries", + "name": "name", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "external_data_source_catalog_entries", + "name": "kind", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "external_data_source_catalog_entries", + "name": "row_estimate", + "position": 4, + "type": "double precision", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "external_data_source_catalog_entries", + "name": "source_note", + "position": 5, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "external_data_source_catalog_entries", + "name": "detected_time_field", + "position": 6, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "external_data_source_catalog_entries", + "name": "fields", + "position": 7, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "external_data_source_catalog_entries", + "name": "exposed", + "position": 8, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "external_data_source_catalog_entries", + "name": "note", + "position": 9, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "external_data_source_catalog_entries", + "name": "time_field_override", + "position": 10, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "external_data_source_catalog_entries", + "name": "field_notes", + "position": 11, + "type": "jsonb", + "notNull": true, + "default": "'{}'::jsonb", + "identity": null + }, + { + "kind": "column", + "table": "external_data_source_catalog_entries", + "name": "seen_at", + "position": 12, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "external_data_sources", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "external_data_sources", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "external_data_sources", + "name": "name", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "external_data_sources", + "name": "kind", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "external_data_sources", + "name": "description", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "external_data_sources", + "name": "environment", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "external_data_sources", + "name": "tags", + "position": 6, + "type": "jsonb", + "notNull": true, + "default": "'[]'::jsonb", + "identity": null + }, + { + "kind": "column", + "table": "external_data_sources", + "name": "agent_access", + "position": 7, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "external_data_sources", + "name": "agent_pii", + "position": 8, + "type": "boolean", + "notNull": true, + "default": "false", + "identity": null + }, + { + "kind": "column", + "table": "external_data_sources", + "name": "config", + "position": 9, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "external_data_sources", + "name": "secret_ciphertext", + "position": 10, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "external_data_sources", + "name": "secret_iv", + "position": 11, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "external_data_sources", + "name": "secret_tag", + "position": 12, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "external_data_sources", + "name": "secret_hint", + "position": 13, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "external_data_sources", + "name": "status", + "position": 14, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "external_data_sources", + "name": "last_checked_at", + "position": 15, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "external_data_sources", + "name": "last_error", + "position": 16, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "external_data_sources", + "name": "catalog_refreshed_at", + "position": 17, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "external_data_sources", + "name": "catalog_error", + "position": 18, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "external_data_sources", + "name": "examples", + "position": 19, + "type": "jsonb", + "notNull": true, + "default": "'[]'::jsonb", + "identity": null + }, + { + "kind": "column", + "table": "external_data_sources", + "name": "created_at", + "position": 20, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "external_data_sources", + "name": "updated_at", + "position": 21, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "external_data_sources", + "name": "created_by", + "position": 22, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "external_data_sources", + "name": "updated_by", + "position": 23, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "feature_requests", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "feature_requests", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "feature_requests", + "name": "user_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "feature_requests", + "name": "area", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "feature_requests", + "name": "subject", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "feature_requests", + "name": "note", + "position": 5, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "feature_requests", + "name": "created_at", + "position": 6, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "fleet_connections", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "fleet_connections", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "fleet_connections", + "name": "base_url", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "fleet_connections", + "name": "token_ciphertext", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "fleet_connections", + "name": "token_iv", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "fleet_connections", + "name": "token_tag", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "fleet_connections", + "name": "organization_name", + "position": 6, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "fleet_connections", + "name": "api_user_name", + "position": 7, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "fleet_connections", + "name": "api_user_role", + "position": 8, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "fleet_connections", + "name": "server_version", + "position": 9, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "fleet_connections", + "name": "license_tier", + "position": 10, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "fleet_connections", + "name": "activity_cursor", + "position": 11, + "type": "bigint", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "fleet_connections", + "name": "activity_gaps", + "position": 12, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "fleet_connections", + "name": "connected_by_user_id", + "position": 13, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "fleet_connections", + "name": "auth_failed_at", + "position": 14, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "fleet_connections", + "name": "lease_until", + "position": 15, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "fleet_connections", + "name": "hold_until", + "position": 16, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "fleet_connections", + "name": "last_success_at", + "position": 17, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "fleet_connections", + "name": "last_error", + "position": 18, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "fleet_connections", + "name": "last_error_at", + "position": 19, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "fleet_connections", + "name": "findings_lease_until", + "position": 20, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "fleet_connections", + "name": "findings_hold_until", + "position": 21, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "fleet_connections", + "name": "findings_synced_at", + "position": 22, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "fleet_connections", + "name": "findings_error", + "position": 23, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "fleet_connections", + "name": "findings_error_at", + "position": 24, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "fleet_connections", + "name": "device_count", + "position": 25, + "type": "integer", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "fleet_connections", + "name": "vulnerability_count", + "position": 26, + "type": "integer", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "fleet_connections", + "name": "created_at", + "position": 27, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "fleet_connections", + "name": "updated_at", + "position": 28, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_connectors", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_connectors", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_connectors", + "name": "source_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_connectors", + "name": "scope_type", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_connectors", + "name": "scope_id", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_connectors", + "name": "project_id", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_connectors", + "name": "logs_enabled", + "position": 6, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "gcp_connectors", + "name": "metrics_enabled", + "position": 7, + "type": "boolean", + "notNull": true, + "default": "false", + "identity": null + }, + { + "kind": "column", + "table": "gcp_connectors", + "name": "secret_ciphertext", + "position": 8, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_connectors", + "name": "secret_iv", + "position": 9, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_connectors", + "name": "secret_tag", + "position": 10, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_connectors", + "name": "secret_hash", + "position": 11, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_connectors", + "name": "last_received_at", + "position": 12, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_connectors", + "name": "last_error", + "position": 13, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_connectors", + "name": "applied_logs_enabled", + "position": 14, + "type": "boolean", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_connectors", + "name": "applied_metrics_enabled", + "position": 15, + "type": "boolean", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_connectors", + "name": "setup_reported_at", + "position": 16, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_connectors", + "name": "metrics_watermark_at", + "position": 17, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_connectors", + "name": "last_metrics_received_at", + "position": 18, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_connectors", + "name": "last_metrics_error", + "position": 19, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_connectors", + "name": "metrics_lease_until", + "position": 20, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_connectors", + "name": "metrics_hold_until", + "position": 21, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_connectors", + "name": "metrics_polled_at", + "position": 22, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_connectors", + "name": "resources_synced_at", + "position": 23, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_connectors", + "name": "last_resources_error", + "position": 24, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_connectors", + "name": "created_by", + "position": 25, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_connectors", + "name": "created_at", + "position": 26, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_connectors", + "name": "updated_at", + "position": 27, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_cost_exports", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_cost_exports", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_cost_exports", + "name": "connector_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_cost_exports", + "name": "table_ref", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_cost_exports", + "name": "billing_account_id", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_cost_exports", + "name": "created_by", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_cost_exports", + "name": "created_at", + "position": 6, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_cost_exports", + "name": "updated_at", + "position": 7, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_resources", + "name": "connector_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_resources", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_resources", + "name": "name", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_resources", + "name": "asset_type", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_resources", + "name": "project_id", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_resources", + "name": "location", + "position": 5, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_resources", + "name": "display_name", + "position": 6, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_resources", + "name": "state", + "position": 7, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_resources", + "name": "labels", + "position": 8, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_resources", + "name": "details", + "position": 9, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_resources", + "name": "resource_created_at", + "position": 10, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_resources", + "name": "resource_updated_at", + "position": 11, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "gcp_resources", + "name": "last_seen_at", + "position": 12, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "investigations", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "investigations", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "investigations", + "name": "status", + "position": 2, + "type": "text", + "notNull": true, + "default": "'investigating'", + "identity": null + }, + { + "kind": "column", + "table": "investigations", + "name": "seeded_by", + "position": 3, + "type": "text", + "notNull": true, + "default": "'user'", + "identity": null + }, + { + "kind": "column", + "table": "investigations", + "name": "subject_json", + "position": 4, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "investigations", + "name": "snapshot_json", + "position": 5, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "investigations", + "name": "incident_kind", + "position": 6, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "investigations", + "name": "incident_id", + "position": 7, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "investigations", + "name": "issue_id", + "position": 8, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "investigations", + "name": "report_json", + "position": 9, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "investigations", + "name": "progress_json", + "position": 10, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "investigations", + "name": "severity", + "position": 11, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "investigations", + "name": "confidence", + "position": 12, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "investigations", + "name": "model", + "position": 13, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "investigations", + "name": "input_tokens", + "position": 14, + "type": "integer", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "investigations", + "name": "output_tokens", + "position": 15, + "type": "integer", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "investigations", + "name": "error", + "position": 16, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "investigations", + "name": "started_at", + "position": 17, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "investigations", + "name": "autonomous_turns", + "position": 18, + "type": "integer", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "investigations", + "name": "created_by", + "position": 19, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "investigations", + "name": "created_at", + "position": 20, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "investigations", + "name": "diagnosed_at", + "position": 21, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "investigations", + "name": "updated_at", + "position": 22, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "issue_escalation_policies", + "name": "org_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "issue_escalation_policies", + "name": "enabled", + "position": 1, + "type": "boolean", + "notNull": true, + "default": "false", + "identity": null + }, + { + "kind": "column", + "table": "issue_escalation_policies", + "name": "rules_json", + "position": 2, + "type": "jsonb", + "notNull": true, + "default": "'[]'", + "identity": null + }, + { + "kind": "column", + "table": "issue_escalation_policies", + "name": "updated_at", + "position": 3, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "issue_escalation_policies", + "name": "updated_by", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "issue_escalations", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "issue_escalations", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "issue_escalations", + "name": "issue_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "issue_escalations", + "name": "severity", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "issue_escalations", + "name": "source", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "issue_escalations", + "name": "reason", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "issue_escalations", + "name": "run_id", + "position": 6, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "issue_escalations", + "name": "investigation_id", + "position": 7, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "issue_escalations", + "name": "payload_json", + "position": 8, + "type": "jsonb", + "notNull": true, + "default": "'{}'", + "identity": null + }, + { + "kind": "column", + "table": "issue_escalations", + "name": "delivery_results_json", + "position": 9, + "type": "jsonb", + "notNull": true, + "default": "'[]'", + "identity": null + }, + { + "kind": "column", + "table": "issue_escalations", + "name": "status", + "position": 10, + "type": "text", + "notNull": true, + "default": "'queued'", + "identity": null + }, + { + "kind": "column", + "table": "issue_escalations", + "name": "attempts", + "position": 11, + "type": "integer", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "issue_escalations", + "name": "claimed_at", + "position": 12, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "issue_escalations", + "name": "dedupe_key", + "position": 13, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "issue_escalations", + "name": "error", + "position": 14, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "issue_escalations", + "name": "created_at", + "position": 15, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "issue_escalations", + "name": "processed_at", + "position": 16, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "linear_feature_settings", + "name": "org_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "linear_feature_settings", + "name": "open_issues_enabled", + "position": 1, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "linear_feature_settings", + "name": "update_comments_enabled", + "position": 2, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "linear_feature_settings", + "name": "reopen_issues_enabled", + "position": 3, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "linear_feature_settings", + "name": "resolve_comments_enabled", + "position": 4, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "linear_feature_settings", + "name": "created_at", + "position": 5, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "linear_feature_settings", + "name": "updated_at", + "position": 6, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "linear_feature_settings", + "name": "updated_by", + "position": 7, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "live_activities", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "live_activities", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "live_activities", + "name": "device_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "live_activities", + "name": "incident_id", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "live_activities", + "name": "activity_id", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "live_activities", + "name": "push_token", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "live_activities", + "name": "ended_at", + "position": 6, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "live_activities", + "name": "ended_reason", + "position": 7, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "live_activities", + "name": "created_at", + "position": 8, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "live_activities", + "name": "updated_at", + "position": 9, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mcp_oauth_authorizations", + "name": "request_id_hash", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mcp_oauth_authorizations", + "name": "client_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mcp_oauth_authorizations", + "name": "client_name", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mcp_oauth_authorizations", + "name": "redirect_uri", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mcp_oauth_authorizations", + "name": "state", + "position": 4, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mcp_oauth_authorizations", + "name": "resource", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mcp_oauth_authorizations", + "name": "scopes", + "position": 6, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mcp_oauth_authorizations", + "name": "code_challenge", + "position": 7, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mcp_oauth_authorizations", + "name": "authorization_code_hash", + "position": 8, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mcp_oauth_authorizations", + "name": "approved_org_id", + "position": 9, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mcp_oauth_authorizations", + "name": "approved_user_id", + "position": 10, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mcp_oauth_authorizations", + "name": "approved_roles", + "position": 11, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mcp_oauth_authorizations", + "name": "approved_user_email", + "position": 12, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mcp_oauth_authorizations", + "name": "approved_at", + "position": 13, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mcp_oauth_authorizations", + "name": "denied_at", + "position": 14, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mcp_oauth_authorizations", + "name": "used_at", + "position": 15, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mcp_oauth_authorizations", + "name": "created_at", + "position": 16, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mcp_oauth_authorizations", + "name": "expires_at", + "position": 17, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mcp_oauth_clients", + "name": "client_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mcp_oauth_clients", + "name": "client_name", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mcp_oauth_clients", + "name": "redirect_uris", + "position": 2, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mcp_oauth_clients", + "name": "client_uri", + "position": 3, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mcp_oauth_clients", + "name": "created_at", + "position": 4, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mcp_oauth_refresh_tokens", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mcp_oauth_refresh_tokens", + "name": "token_hash", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mcp_oauth_refresh_tokens", + "name": "family_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mcp_oauth_refresh_tokens", + "name": "client_id", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mcp_oauth_refresh_tokens", + "name": "resource", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mcp_oauth_refresh_tokens", + "name": "scopes", + "position": 5, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mcp_oauth_refresh_tokens", + "name": "org_id", + "position": 6, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mcp_oauth_refresh_tokens", + "name": "user_id", + "position": 7, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mcp_oauth_refresh_tokens", + "name": "roles", + "position": 8, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mcp_oauth_refresh_tokens", + "name": "user_email", + "position": 9, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mcp_oauth_refresh_tokens", + "name": "access_key_id", + "position": 10, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mcp_oauth_refresh_tokens", + "name": "replaced_by_id", + "position": 11, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mcp_oauth_refresh_tokens", + "name": "revoked_at", + "position": 12, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mcp_oauth_refresh_tokens", + "name": "created_at", + "position": 13, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mcp_oauth_refresh_tokens", + "name": "expires_at", + "position": 14, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mcp_oauth_refresh_tokens", + "name": "family_expires_at", + "position": 15, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mobile_devices", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mobile_devices", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mobile_devices", + "name": "user_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mobile_devices", + "name": "platform", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mobile_devices", + "name": "token", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mobile_devices", + "name": "environment", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mobile_devices", + "name": "bundle_id", + "position": 6, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mobile_devices", + "name": "app_version", + "position": 7, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mobile_devices", + "name": "live_activity_start_token", + "position": 8, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mobile_devices", + "name": "device_name", + "position": 9, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mobile_devices", + "name": "preferences", + "position": 10, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mobile_devices", + "name": "disabled_at", + "position": 11, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mobile_devices", + "name": "disabled_reason", + "position": 12, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mobile_devices", + "name": "last_pushed_at", + "position": 13, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mobile_devices", + "name": "last_seen_at", + "position": 14, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mobile_devices", + "name": "created_at", + "position": 15, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "mobile_devices", + "name": "updated_at", + "position": 16, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oauth_auth_states", + "name": "state", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oauth_auth_states", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oauth_auth_states", + "name": "provider", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oauth_auth_states", + "name": "initiated_by_user_id", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oauth_auth_states", + "name": "redirect_uri", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oauth_auth_states", + "name": "return_to", + "position": 5, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oauth_auth_states", + "name": "code_verifier", + "position": 6, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oauth_auth_states", + "name": "github_installation_ids", + "position": 7, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oauth_auth_states", + "name": "created_at", + "position": 8, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oauth_auth_states", + "name": "expires_at", + "position": 9, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oauth_connections", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oauth_connections", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oauth_connections", + "name": "source_id", + "position": 2, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oauth_connections", + "name": "provider", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oauth_connections", + "name": "external_user_id", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oauth_connections", + "name": "external_user_email", + "position": 5, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oauth_connections", + "name": "external_account_name", + "position": 6, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oauth_connections", + "name": "granted_accounts_json", + "position": 7, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oauth_connections", + "name": "connected_by_user_id", + "position": 8, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oauth_connections", + "name": "scope", + "position": 9, + "type": "text", + "notNull": true, + "default": "''", + "identity": null + }, + { + "kind": "column", + "table": "oauth_connections", + "name": "access_token_ciphertext", + "position": 10, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oauth_connections", + "name": "access_token_iv", + "position": 11, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oauth_connections", + "name": "access_token_tag", + "position": 12, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oauth_connections", + "name": "refresh_token_ciphertext", + "position": 13, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oauth_connections", + "name": "refresh_token_iv", + "position": 14, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oauth_connections", + "name": "refresh_token_tag", + "position": 15, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oauth_connections", + "name": "expires_at", + "position": 16, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oauth_connections", + "name": "revoked_at", + "position": 17, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oauth_connections", + "name": "created_at", + "position": 18, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oauth_connections", + "name": "updated_at", + "position": 19, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "onboarding_agent_runs", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "onboarding_agent_runs", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "onboarding_agent_runs", + "name": "user_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "onboarding_agent_runs", + "name": "status", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "onboarding_agent_runs", + "name": "stages", + "position": 4, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "onboarding_agent_runs", + "name": "service_names", + "position": 5, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "onboarding_agent_runs", + "name": "trace_id", + "position": 6, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "onboarding_agent_runs", + "name": "handoff_code_hash", + "position": 7, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "onboarding_agent_runs", + "name": "api_key_id", + "position": 8, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "onboarding_agent_runs", + "name": "last_reported_at", + "position": 9, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "onboarding_agent_runs", + "name": "created_at", + "position": 10, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "onboarding_agent_runs", + "name": "expires_at", + "position": 11, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "onboarding_agent_runs", + "name": "updated_at", + "position": 12, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oncall_overrides", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oncall_overrides", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oncall_overrides", + "name": "schedule_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oncall_overrides", + "name": "user_id", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oncall_overrides", + "name": "starts_at", + "position": 4, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oncall_overrides", + "name": "ends_at", + "position": 5, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oncall_overrides", + "name": "created_by", + "position": 6, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oncall_overrides", + "name": "created_at", + "position": 7, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oncall_schedules", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oncall_schedules", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oncall_schedules", + "name": "name", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oncall_schedules", + "name": "description", + "position": 3, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oncall_schedules", + "name": "time_zone", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oncall_schedules", + "name": "layers_json", + "position": 5, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oncall_schedules", + "name": "calendar_feed_token_hash", + "position": 6, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oncall_schedules", + "name": "calendar_feed_created_at", + "position": 7, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oncall_schedules", + "name": "created_at", + "position": 8, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oncall_schedules", + "name": "updated_at", + "position": 9, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oncall_schedules", + "name": "created_by", + "position": 10, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "oncall_schedules", + "name": "updated_by", + "position": 11, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "openrouter_cost_connections", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "openrouter_cost_connections", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "openrouter_cost_connections", + "name": "key_ciphertext", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "openrouter_cost_connections", + "name": "key_iv", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "openrouter_cost_connections", + "name": "key_tag", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "openrouter_cost_connections", + "name": "key_label", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "openrouter_cost_connections", + "name": "account_id", + "position": 6, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "openrouter_cost_connections", + "name": "created_at", + "position": 7, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "openrouter_cost_connections", + "name": "updated_at", + "position": 8, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "openrouter_cost_connections", + "name": "updated_by", + "position": 9, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_billing_links", + "name": "org_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_billing_links", + "name": "billing_org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_billing_links", + "name": "linked_by", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_billing_links", + "name": "created_at", + "position": 3, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_clickhouse_schema_apply_runs", + "name": "org_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_clickhouse_schema_apply_runs", + "name": "workflow_instance_id", + "position": 1, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_clickhouse_schema_apply_runs", + "name": "status", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_clickhouse_schema_apply_runs", + "name": "phase", + "position": 3, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_clickhouse_schema_apply_runs", + "name": "current_migration", + "position": 4, + "type": "integer", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_clickhouse_schema_apply_runs", + "name": "steps_total", + "position": 5, + "type": "integer", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_clickhouse_schema_apply_runs", + "name": "steps_done", + "position": 6, + "type": "integer", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_clickhouse_schema_apply_runs", + "name": "applied_versions", + "position": 7, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_clickhouse_schema_apply_runs", + "name": "skipped", + "position": 8, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_clickhouse_schema_apply_runs", + "name": "error_message", + "position": 9, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_clickhouse_schema_apply_runs", + "name": "started_at", + "position": 10, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_clickhouse_schema_apply_runs", + "name": "finished_at", + "position": 11, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_clickhouse_schema_apply_runs", + "name": "created_at", + "position": 12, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_clickhouse_schema_apply_runs", + "name": "updated_at", + "position": 13, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_clickhouse_settings", + "name": "org_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_clickhouse_settings", + "name": "ch_url", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_clickhouse_settings", + "name": "ch_user", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_clickhouse_settings", + "name": "ch_password_ciphertext", + "position": 3, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_clickhouse_settings", + "name": "ch_password_iv", + "position": 4, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_clickhouse_settings", + "name": "ch_password_tag", + "position": 5, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_clickhouse_settings", + "name": "ch_database", + "position": 6, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_clickhouse_settings", + "name": "sync_status", + "position": 7, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_clickhouse_settings", + "name": "last_sync_at", + "position": 8, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_clickhouse_settings", + "name": "last_sync_error", + "position": 9, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_clickhouse_settings", + "name": "schema_version", + "position": 10, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_clickhouse_settings", + "name": "created_at", + "position": 11, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_clickhouse_settings", + "name": "updated_at", + "position": 12, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_clickhouse_settings", + "name": "created_by", + "position": 13, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_clickhouse_settings", + "name": "updated_by", + "position": 14, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_directory_groups", + "name": "org_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_directory_groups", + "name": "directory_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_directory_groups", + "name": "group_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_directory_groups", + "name": "display_name", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_directory_groups", + "name": "updated_at", + "position": 4, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_directory_groups", + "name": "deleted_at", + "position": 5, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_erasures", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_erasures", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_erasures", + "name": "kind", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_erasures", + "name": "target", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_erasures", + "name": "job_id", + "position": 4, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_erasures", + "name": "attempts", + "position": 5, + "type": "integer", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "org_erasures", + "name": "last_error", + "position": 6, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_erasures", + "name": "next_attempt_at", + "position": 7, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_erasures", + "name": "created_at", + "position": 8, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_attribute_mappings", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_attribute_mappings", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_attribute_mappings", + "name": "name", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_attribute_mappings", + "name": "source_context", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_attribute_mappings", + "name": "source_key", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_attribute_mappings", + "name": "target_key", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_attribute_mappings", + "name": "operation", + "position": 6, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_attribute_mappings", + "name": "enabled", + "position": 7, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_attribute_mappings", + "name": "created_at", + "position": 8, + "type": "timestamp with time zone", + "notNull": true, + "default": "now()", + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_attribute_mappings", + "name": "updated_at", + "position": 9, + "type": "timestamp with time zone", + "notNull": true, + "default": "now()", + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_keys", + "name": "org_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_keys", + "name": "public_key", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_keys", + "name": "public_key_hash", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_keys", + "name": "private_key_ciphertext", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_keys", + "name": "private_key_iv", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_keys", + "name": "private_key_tag", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_keys", + "name": "private_key_hash", + "position": 6, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_keys", + "name": "public_rotated_at", + "position": 7, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_keys", + "name": "private_rotated_at", + "position": 8, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_keys", + "name": "created_at", + "position": 9, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_keys", + "name": "updated_at", + "position": 10, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_keys", + "name": "created_by", + "position": 11, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_keys", + "name": "updated_by", + "position": 12, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_rule_settings", + "name": "org_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_rule_settings", + "name": "hash_salt", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_rule_settings", + "name": "created_at", + "position": 2, + "type": "timestamp with time zone", + "notNull": true, + "default": "now()", + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_rule_stats", + "name": "org_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_rule_stats", + "name": "rule_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_rule_stats", + "name": "bucket", + "position": 2, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_rule_stats", + "name": "signal", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_rule_stats", + "name": "matched", + "position": 4, + "type": "bigint", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_rule_stats", + "name": "dropped", + "position": 5, + "type": "bigint", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_rule_stats", + "name": "dropped_bytes", + "position": 6, + "type": "bigint", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_rule_stats", + "name": "redacted_values", + "position": 7, + "type": "bigint", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_rule_stats", + "name": "parse_failed", + "position": 8, + "type": "bigint", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_rules", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_rules", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_rules", + "name": "name", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_rules", + "name": "enabled", + "position": 3, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_rules", + "name": "position", + "position": 4, + "type": "integer", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_rules", + "name": "spec_json", + "position": 5, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_rules", + "name": "created_at", + "position": 6, + "type": "timestamp with time zone", + "notNull": true, + "default": "now()", + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_rules", + "name": "updated_at", + "position": 7, + "type": "timestamp with time zone", + "notNull": true, + "default": "now()", + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_sampling_policies", + "name": "org_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_sampling_policies", + "name": "trace_sample_ratio", + "position": 1, + "type": "double precision", + "notNull": true, + "default": "1", + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_sampling_policies", + "name": "always_keep_error_spans", + "position": 2, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_sampling_policies", + "name": "always_keep_slow_spans_ms", + "position": 3, + "type": "integer", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_sampling_policies", + "name": "created_at", + "position": 4, + "type": "timestamp with time zone", + "notNull": true, + "default": "now()", + "identity": null + }, + { + "kind": "column", + "table": "org_ingest_sampling_policies", + "name": "updated_at", + "position": 5, + "type": "timestamp with time zone", + "notNull": true, + "default": "now()", + "identity": null + }, + { + "kind": "column", + "table": "org_onboarding_state", + "name": "org_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_onboarding_state", + "name": "user_id", + "position": 1, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_onboarding_state", + "name": "email", + "position": 2, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_onboarding_state", + "name": "role", + "position": 3, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_onboarding_state", + "name": "demo_data_requested", + "position": 4, + "type": "boolean", + "notNull": true, + "default": "false", + "identity": null + }, + { + "kind": "column", + "table": "org_onboarding_state", + "name": "onboarding_completed_at", + "position": 5, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_onboarding_state", + "name": "checklist_dismissed_at", + "position": 6, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_onboarding_state", + "name": "first_data_received_at", + "position": 7, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_onboarding_state", + "name": "welcome_email_sent_at", + "position": 8, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_onboarding_state", + "name": "connect_nudge_email_sent_at", + "position": 9, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_onboarding_state", + "name": "stalled_email_sent_at", + "position": 10, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_onboarding_state", + "name": "activation_email_sent_at", + "position": 11, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_onboarding_state", + "name": "reward_claimed_at", + "position": 12, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_onboarding_state", + "name": "reward_reserved_at", + "position": 13, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_onboarding_state", + "name": "created_at", + "position": 14, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_onboarding_state", + "name": "updated_at", + "position": 15, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_openrouter_keys", + "name": "org_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_openrouter_keys", + "name": "key_ciphertext", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_openrouter_keys", + "name": "key_iv", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_openrouter_keys", + "name": "key_tag", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_openrouter_keys", + "name": "key_hint", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_openrouter_keys", + "name": "created_at", + "position": 5, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_openrouter_keys", + "name": "updated_at", + "position": 6, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_openrouter_keys", + "name": "updated_by", + "position": 7, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_recommendation_issues", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_recommendation_issues", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_recommendation_issues", + "name": "number", + "position": 2, + "type": "integer", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_recommendation_issues", + "name": "recommendation_key", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_recommendation_issues", + "name": "kind", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_recommendation_issues", + "name": "source_key", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_recommendation_issues", + "name": "canonical_key", + "position": 6, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_recommendation_issues", + "name": "status", + "position": 7, + "type": "text", + "notNull": true, + "default": "'open'", + "identity": null + }, + { + "kind": "column", + "table": "org_recommendation_issues", + "name": "usage_count", + "position": 8, + "type": "integer", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "org_recommendation_issues", + "name": "opened_at", + "position": 9, + "type": "timestamp with time zone", + "notNull": true, + "default": "now()", + "identity": null + }, + { + "kind": "column", + "table": "org_recommendation_issues", + "name": "updated_at", + "position": 10, + "type": "timestamp with time zone", + "notNull": true, + "default": "now()", + "identity": null + }, + { + "kind": "column", + "table": "org_recommendation_issues", + "name": "resolved_at", + "position": 11, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_sso_connections", + "name": "org_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_sso_connections", + "name": "clerk_connection_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_sso_connections", + "name": "clerk_directory_id", + "position": 2, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_sso_connections", + "name": "created_at", + "position": 3, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_sso_connections", + "name": "created_by", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_sso_connections", + "name": "updated_at", + "position": 5, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_sso_domains", + "name": "org_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_sso_domains", + "name": "domain", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_sso_domains", + "name": "challenge", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_sso_domains", + "name": "status", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_sso_domains", + "name": "clerk_domain_id", + "position": 4, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_sso_domains", + "name": "verified_at", + "position": 5, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_sso_domains", + "name": "created_at", + "position": 6, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_sso_domains", + "name": "created_by", + "position": 7, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_support_channels", + "name": "org_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_support_channels", + "name": "slack_channel_id", + "position": 1, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_support_channels", + "name": "slack_channel_name", + "position": 2, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_support_channels", + "name": "reservation_id", + "position": 3, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_support_channels", + "name": "reserved_at", + "position": 4, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_support_channels", + "name": "created_by_user_id", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_support_channels", + "name": "created_at", + "position": 6, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "org_support_channels", + "name": "updated_at", + "position": 7, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_connections", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_connections", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_connections", + "name": "source_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_connections", + "name": "ps_organization", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_connections", + "name": "connected_by_user_id", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_connections", + "name": "scrape_target_id", + "position": 5, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_connections", + "name": "webhook_secret_ciphertext", + "position": 6, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_connections", + "name": "webhook_secret_iv", + "position": 7, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_connections", + "name": "webhook_secret_tag", + "position": 8, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_connections", + "name": "detected_permissions_json", + "position": 9, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_connections", + "name": "metrics_enabled", + "position": 10, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "planetscale_connections", + "name": "events_enabled", + "position": 11, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "planetscale_connections", + "name": "last_inventory_at", + "position": 12, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_connections", + "name": "last_inventory_error", + "position": 13, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_connections", + "name": "created_at", + "position": 14, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_connections", + "name": "updated_at", + "position": 15, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_databases", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_databases", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_databases", + "name": "database_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_databases", + "name": "name", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_databases", + "name": "kind", + "position": 4, + "type": "text", + "notNull": true, + "default": "'mysql'", + "identity": null + }, + { + "kind": "column", + "table": "planetscale_databases", + "name": "state", + "position": 5, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_databases", + "name": "region", + "position": 6, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_databases", + "name": "plan", + "position": 7, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_databases", + "name": "branches_json", + "position": 8, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_databases", + "name": "webhook_id", + "position": 9, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_databases", + "name": "webhook_secret_ciphertext", + "position": 10, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_databases", + "name": "webhook_secret_iv", + "position": 11, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_databases", + "name": "webhook_secret_tag", + "position": 12, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_databases", + "name": "webhook_error", + "position": 13, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_databases", + "name": "deleted_at", + "position": 14, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_databases", + "name": "created_at", + "position": 15, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_databases", + "name": "updated_at", + "position": 16, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_events", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_events", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_events", + "name": "database_id", + "position": 2, + "type": "text", + "notNull": true, + "default": "''", + "identity": null + }, + { + "kind": "column", + "table": "planetscale_events", + "name": "database_name", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_events", + "name": "branch_name", + "position": 4, + "type": "text", + "notNull": true, + "default": "''", + "identity": null + }, + { + "kind": "column", + "table": "planetscale_events", + "name": "category", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_events", + "name": "event_type", + "position": 6, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_events", + "name": "state", + "position": 7, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_events", + "name": "external_id", + "position": 8, + "type": "text", + "notNull": true, + "default": "''", + "identity": null + }, + { + "kind": "column", + "table": "planetscale_events", + "name": "title", + "position": 9, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_events", + "name": "source", + "position": 10, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_events", + "name": "actor_login", + "position": 11, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_events", + "name": "url", + "position": 12, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_events", + "name": "payload_json", + "position": 13, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_events", + "name": "occurred_at", + "position": 14, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_events", + "name": "created_at", + "position": 15, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_issue_receipts", + "name": "org_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_issue_receipts", + "name": "event_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_issue_receipts", + "name": "processed_at", + "position": 2, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_poll_state", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_poll_state", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_poll_state", + "name": "dataset", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_poll_state", + "name": "database_id", + "position": 3, + "type": "text", + "notNull": true, + "default": "''", + "identity": null + }, + { + "kind": "column", + "table": "planetscale_poll_state", + "name": "enabled", + "position": 4, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "planetscale_poll_state", + "name": "watermark_at", + "position": 5, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_poll_state", + "name": "last_success_at", + "position": 6, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_poll_state", + "name": "last_error", + "position": 7, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_poll_state", + "name": "last_error_at", + "position": 8, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_poll_state", + "name": "lease_until", + "position": 9, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_poll_state", + "name": "hold_until", + "position": 10, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_poll_state", + "name": "created_at", + "position": 11, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "planetscale_poll_state", + "name": "updated_at", + "position": 12, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_edits", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_edits", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_edits", + "name": "reply_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_edits", + "name": "seq", + "position": 3, + "type": "integer", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_edits", + "name": "path", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_edits", + "name": "old_text", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_edits", + "name": "new_text", + "position": 6, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_edits", + "name": "created_at", + "position": 7, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_finding_embeddings", + "name": "finding_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_finding_embeddings", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_finding_embeddings", + "name": "repository_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_finding_embeddings", + "name": "model", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_finding_embeddings", + "name": "embedding", + "position": 4, + "type": "real[]", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_finding_embeddings", + "name": "created_at", + "position": 5, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_findings", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_findings", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_findings", + "name": "repository_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_findings", + "name": "number", + "position": 3, + "type": "integer", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_findings", + "name": "review_id", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_findings", + "name": "handle", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_findings", + "name": "path", + "position": 6, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_findings", + "name": "line", + "position": 7, + "type": "integer", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_findings", + "name": "category", + "position": 8, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_findings", + "name": "severity", + "position": 9, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_findings", + "name": "title", + "position": 10, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_findings", + "name": "status", + "position": 11, + "type": "text", + "notNull": true, + "default": "'open'", + "identity": null + }, + { + "kind": "column", + "table": "pr_review_findings", + "name": "comment_id", + "position": 12, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_findings", + "name": "resolved_sha", + "position": 13, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_findings", + "name": "reactions_up", + "position": 14, + "type": "integer", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "pr_review_findings", + "name": "reactions_down", + "position": 15, + "type": "integer", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "pr_review_findings", + "name": "created_at", + "position": 16, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_findings", + "name": "updated_at", + "position": 17, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_merge_steps", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_merge_steps", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_merge_steps", + "name": "repository_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_merge_steps", + "name": "number", + "position": 3, + "type": "integer", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_merge_steps", + "name": "key", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_merge_steps", + "name": "kind", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_merge_steps", + "name": "title", + "position": 6, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_merge_steps", + "name": "source", + "position": 7, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_merge_steps", + "name": "path", + "position": 8, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_merge_steps", + "name": "status", + "position": 9, + "type": "text", + "notNull": true, + "default": "'open'", + "identity": null + }, + { + "kind": "column", + "table": "pr_review_merge_steps", + "name": "done_by", + "position": 10, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_merge_steps", + "name": "done_at", + "position": 11, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_merge_steps", + "name": "reminded_at", + "position": 12, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_merge_steps", + "name": "first_review_id", + "position": 13, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_merge_steps", + "name": "last_review_id", + "position": 14, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_merge_steps", + "name": "created_at", + "position": 15, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_merge_steps", + "name": "updated_at", + "position": 16, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_replies", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_replies", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_replies", + "name": "repository_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_replies", + "name": "number", + "position": 3, + "type": "integer", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_replies", + "name": "comment_id", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_replies", + "name": "surface", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_replies", + "name": "thread_root_id", + "position": 6, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_replies", + "name": "author_login", + "position": 7, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_replies", + "name": "command", + "position": 8, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_replies", + "name": "head_sha", + "position": 9, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_replies", + "name": "status", + "position": 10, + "type": "text", + "notNull": true, + "default": "'queued'", + "identity": null + }, + { + "kind": "column", + "table": "pr_review_replies", + "name": "session_id", + "position": 11, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_replies", + "name": "reply_url", + "position": 12, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_replies", + "name": "commit_sha", + "position": 13, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_replies", + "name": "error", + "position": 14, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_replies", + "name": "created_at", + "position": 15, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_replies", + "name": "updated_at", + "position": 16, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_settings", + "name": "org_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_settings", + "name": "model", + "position": 1, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_settings", + "name": "defaults", + "position": 2, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_settings", + "name": "updated_at", + "position": 3, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_review_settings", + "name": "updated_by", + "position": 4, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_reviews", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_reviews", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_reviews", + "name": "repository_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_reviews", + "name": "number", + "position": 3, + "type": "integer", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_reviews", + "name": "head_sha", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_reviews", + "name": "base_sha", + "position": 5, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_reviews", + "name": "url", + "position": 6, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_reviews", + "name": "title", + "position": 7, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_reviews", + "name": "author_login", + "position": 8, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_reviews", + "name": "status", + "position": 9, + "type": "text", + "notNull": true, + "default": "'queued'", + "identity": null + }, + { + "kind": "column", + "table": "pr_reviews", + "name": "skip_reason", + "position": 10, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_reviews", + "name": "session_id", + "position": 11, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_reviews", + "name": "comment_attempt", + "position": 12, + "type": "integer", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "pr_reviews", + "name": "held_back", + "position": 13, + "type": "integer", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "pr_reviews", + "name": "report_json", + "position": 14, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_reviews", + "name": "score", + "position": 15, + "type": "integer", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_reviews", + "name": "check_run_url", + "position": 16, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_reviews", + "name": "comment_url", + "position": 17, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_reviews", + "name": "review_url", + "position": 18, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_reviews", + "name": "publish_error", + "position": 19, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_reviews", + "name": "error", + "position": 20, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_reviews", + "name": "model", + "position": 21, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_reviews", + "name": "input_tokens", + "position": 22, + "type": "integer", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_reviews", + "name": "output_tokens", + "position": 23, + "type": "integer", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_reviews", + "name": "cost_microusd", + "position": 24, + "type": "integer", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_reviews", + "name": "started_at", + "position": 25, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_reviews", + "name": "finished_at", + "position": 26, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_reviews", + "name": "merged_at", + "position": 27, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_reviews", + "name": "telemetry_json", + "position": 28, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_reviews", + "name": "merge_commit_sha", + "position": 29, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_reviews", + "name": "post_merge_status", + "position": 30, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_reviews", + "name": "post_merge_after", + "position": 31, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_reviews", + "name": "post_merge_json", + "position": 32, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_reviews", + "name": "created_at", + "position": 33, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "pr_reviews", + "name": "updated_at", + "position": 34, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "railway_connections", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "railway_connections", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "railway_connections", + "name": "source_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "railway_connections", + "name": "token_ciphertext", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "railway_connections", + "name": "token_iv", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "railway_connections", + "name": "token_tag", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "railway_connections", + "name": "workspace_names", + "position": 6, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "railway_connections", + "name": "connected_by_user_id", + "position": 7, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "railway_connections", + "name": "auth_failed_at", + "position": 8, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "railway_connections", + "name": "discovered_at", + "position": 9, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "railway_connections", + "name": "lease_until", + "position": 10, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "railway_connections", + "name": "hold_until", + "position": 11, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "railway_connections", + "name": "last_success_at", + "position": 12, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "railway_connections", + "name": "last_error", + "position": 13, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "railway_connections", + "name": "last_error_at", + "position": 14, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "railway_connections", + "name": "created_at", + "position": 15, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "railway_connections", + "name": "updated_at", + "position": 16, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "railway_environments", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "railway_environments", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "railway_environments", + "name": "connection_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "railway_environments", + "name": "project_id", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "railway_environments", + "name": "project_name", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "railway_environments", + "name": "environment_id", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "railway_environments", + "name": "environment_name", + "position": 6, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "railway_environments", + "name": "services_json", + "position": 7, + "type": "text", + "notNull": true, + "default": "'{}'", + "identity": null + }, + { + "kind": "column", + "table": "railway_environments", + "name": "enabled", + "position": 8, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "railway_environments", + "name": "watermark_at", + "position": 9, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "railway_environments", + "name": "last_success_at", + "position": 10, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "railway_environments", + "name": "last_error", + "position": 11, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "railway_environments", + "name": "last_error_at", + "position": 12, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "railway_environments", + "name": "created_at", + "position": 13, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "railway_environments", + "name": "updated_at", + "position": 14, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "saved_views", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "saved_views", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "saved_views", + "name": "owner_user_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "saved_views", + "name": "surface", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "saved_views", + "name": "name", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "saved_views", + "name": "state", + "position": 5, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "saved_views", + "name": "visibility", + "position": 6, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "saved_views", + "name": "created_at", + "position": 7, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "saved_views", + "name": "updated_at", + "position": 8, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "scrape_target_checks", + "name": "id", + "position": 0, + "type": "integer", + "notNull": true, + "default": null, + "identity": "by default" + }, + { + "kind": "column", + "table": "scrape_target_checks", + "name": "target_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "scrape_target_checks", + "name": "org_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "scrape_target_checks", + "name": "sub_target_key", + "position": 3, + "type": "text", + "notNull": true, + "default": "''", + "identity": null + }, + { + "kind": "column", + "table": "scrape_target_checks", + "name": "checked_at", + "position": 4, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "scrape_target_checks", + "name": "error", + "position": 5, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "scrape_target_checks", + "name": "duration_ms", + "position": 6, + "type": "integer", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "scrape_target_checks", + "name": "samples_scraped", + "position": 7, + "type": "integer", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "scrape_target_checks", + "name": "samples_post_relabel", + "position": 8, + "type": "integer", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "scrape_targets", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "scrape_targets", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "scrape_targets", + "name": "source_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "scrape_targets", + "name": "name", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "scrape_targets", + "name": "service_name", + "position": 4, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "scrape_targets", + "name": "url", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "scrape_targets", + "name": "target_type", + "position": 6, + "type": "text", + "notNull": true, + "default": "'prometheus'", + "identity": null + }, + { + "kind": "column", + "table": "scrape_targets", + "name": "discovery_config_json", + "position": 7, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "scrape_targets", + "name": "scrape_interval_seconds", + "position": 8, + "type": "integer", + "notNull": true, + "default": "15", + "identity": null + }, + { + "kind": "column", + "table": "scrape_targets", + "name": "labels_json", + "position": 9, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "scrape_targets", + "name": "auth_type", + "position": 10, + "type": "text", + "notNull": true, + "default": "'none'", + "identity": null + }, + { + "kind": "column", + "table": "scrape_targets", + "name": "managed_by", + "position": 11, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "scrape_targets", + "name": "auth_credentials_ciphertext", + "position": 12, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "scrape_targets", + "name": "auth_credentials_iv", + "position": 13, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "scrape_targets", + "name": "auth_credentials_tag", + "position": 14, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "scrape_targets", + "name": "enabled", + "position": 15, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "scrape_targets", + "name": "last_scrape_at", + "position": 16, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "scrape_targets", + "name": "last_scrape_error", + "position": 17, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "scrape_targets", + "name": "created_at", + "position": 18, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "scrape_targets", + "name": "updated_at", + "position": 19, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "search_console_sites", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "search_console_sites", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "search_console_sites", + "name": "oauth_connection_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "search_console_sites", + "name": "site_url", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "search_console_sites", + "name": "permission_level", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "search_console_sites", + "name": "enabled", + "position": 5, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "search_console_sites", + "name": "watermark_date", + "position": 6, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "search_console_sites", + "name": "backfill_date", + "position": 7, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "search_console_sites", + "name": "last_synced_at", + "position": 8, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "search_console_sites", + "name": "last_error", + "position": 9, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "search_console_sites", + "name": "lease_until", + "position": 10, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "search_console_sites", + "name": "next_attempt_at", + "position": 11, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "search_console_sites", + "name": "consecutive_failures", + "position": 12, + "type": "integer", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "search_console_sites", + "name": "created_at", + "position": 13, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "search_console_sites", + "name": "updated_at", + "position": 14, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_events", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_events", + "name": "run_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_events", + "name": "org_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_events", + "name": "at", + "position": 3, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_events", + "name": "kind", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_events", + "name": "role", + "position": 5, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_events", + "name": "agent_id", + "position": 6, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_events", + "name": "outcome", + "position": 7, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_events", + "name": "detail", + "position": 8, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_events", + "name": "input_tokens", + "position": 9, + "type": "bigint", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_events", + "name": "output_tokens", + "position": 10, + "type": "bigint", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_findings", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_findings", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_findings", + "name": "target_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_findings", + "name": "fingerprint", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_findings", + "name": "verdict", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_findings", + "name": "overall_severity", + "position": 5, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_findings", + "name": "estimated_severity", + "position": 6, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_findings", + "name": "record", + "position": 7, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_findings", + "name": "status", + "position": 8, + "type": "text", + "notNull": true, + "default": "'open'", + "identity": null + }, + { + "kind": "column", + "table": "security_audit_findings", + "name": "first_seen_run_id", + "position": 9, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_findings", + "name": "last_seen_run_id", + "position": 10, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_findings", + "name": "first_seen_ref", + "position": 11, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_findings", + "name": "last_seen_ref", + "position": 12, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_findings", + "name": "fixed_run_id", + "position": 13, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_findings", + "name": "status_reason", + "position": 14, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_findings", + "name": "status_changed_by", + "position": 15, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_findings", + "name": "status_changed_at", + "position": 16, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_findings", + "name": "created_at", + "position": 17, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_findings", + "name": "updated_at", + "position": 18, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_org_reservations", + "name": "run_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_org_reservations", + "name": "agent_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_org_reservations", + "name": "org_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_org_reservations", + "name": "cost_usd", + "position": 3, + "type": "double precision", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_org_reservations", + "name": "sandbox_fee_usd", + "position": 4, + "type": "double precision", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "security_audit_org_reservations", + "name": "created_at", + "position": 5, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_org_settings", + "name": "org_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_org_settings", + "name": "monthly_spend_limit_usd", + "position": 1, + "type": "integer", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_org_settings", + "name": "discovery_model", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_org_settings", + "name": "validation_model", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_org_settings", + "name": "updated_by", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_org_settings", + "name": "updated_at", + "position": 5, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_run_findings", + "name": "run_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_run_findings", + "name": "fingerprint", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_run_findings", + "name": "org_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_run_findings", + "name": "verdict", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_run_findings", + "name": "overall_severity", + "position": 4, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_run_findings", + "name": "estimated_severity", + "position": 5, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_run_findings", + "name": "record", + "position": 6, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_runs", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_runs", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_runs", + "name": "target_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_runs", + "name": "kind", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_runs", + "name": "source_ref", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_runs", + "name": "profile", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_runs", + "name": "scope_paths", + "position": 6, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_runs", + "name": "budget", + "position": 7, + "type": "integer", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_runs", + "name": "metadata", + "position": 8, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_runs", + "name": "status", + "position": 9, + "type": "text", + "notNull": true, + "default": "'in_progress'", + "identity": null + }, + { + "kind": "column", + "table": "security_audit_runs", + "name": "incomplete_reason", + "position": 10, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_runs", + "name": "architecture_md", + "position": 11, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_runs", + "name": "reports", + "position": 12, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_runs", + "name": "execution_profile", + "position": 13, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_runs", + "name": "invocations_spent", + "position": 14, + "type": "integer", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "security_audit_runs", + "name": "input_tokens", + "position": 15, + "type": "bigint", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "security_audit_runs", + "name": "output_tokens", + "position": 16, + "type": "bigint", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "security_audit_runs", + "name": "cost_usd", + "position": 17, + "type": "double precision", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_runs", + "name": "sandbox_usd", + "position": 18, + "type": "double precision", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "security_audit_runs", + "name": "discovery_model", + "position": 19, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_runs", + "name": "validation_model", + "position": 20, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_runs", + "name": "workflow_instance_id", + "position": 21, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_runs", + "name": "started_at", + "position": 22, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_runs", + "name": "finished_at", + "position": 23, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_runs", + "name": "error", + "position": 24, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_targets", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_targets", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_targets", + "name": "repository", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_targets", + "name": "vcs_repository_id", + "position": 3, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_targets", + "name": "branch", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_targets", + "name": "enabled", + "position": 5, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "security_audit_targets", + "name": "profile", + "position": 6, + "type": "text", + "notNull": true, + "default": "'deep'", + "identity": null + }, + { + "kind": "column", + "table": "security_audit_targets", + "name": "scope_paths", + "position": 7, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_targets", + "name": "slice_interval_hours", + "position": 8, + "type": "integer", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_targets", + "name": "revalidate_on_push", + "position": 9, + "type": "boolean", + "notNull": true, + "default": "false", + "identity": null + }, + { + "kind": "column", + "table": "security_audit_targets", + "name": "budget_per_run", + "position": 10, + "type": "integer", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_targets", + "name": "monthly_invocation_budget", + "position": 11, + "type": "integer", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_targets", + "name": "discovery_model", + "position": 12, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_targets", + "name": "validation_model", + "position": 13, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_targets", + "name": "created_by", + "position": 14, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_targets", + "name": "created_at", + "position": 15, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_targets", + "name": "updated_at", + "position": 16, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_units", + "name": "run_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_units", + "name": "coverage_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_units", + "name": "org_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_units", + "name": "status", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_units", + "name": "wave", + "position": 4, + "type": "integer", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_units", + "name": "agent_id", + "position": 5, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "security_audit_units", + "name": "unit", + "position": 6, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "service_map_world_entities", + "name": "org_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "service_map_world_entities", + "name": "entity_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "service_map_world_entities", + "name": "kind", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "service_map_world_entities", + "name": "data", + "position": 3, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "service_map_world_entities", + "name": "revision", + "position": 4, + "type": "integer", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "service_map_world_entities", + "name": "created_at", + "position": 5, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "service_map_world_entities", + "name": "updated_at", + "position": 6, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "service_map_world_entities", + "name": "updated_by", + "position": 7, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "service_map_world_entities", + "name": "deleted_at", + "position": 8, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "slos", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "slos", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "slos", + "name": "name", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "slos", + "name": "description", + "position": 3, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "slos", + "name": "service_name", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "slos", + "name": "environments_json", + "position": 5, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "slos", + "name": "sli_json", + "position": 6, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "slos", + "name": "target_percent", + "position": 7, + "type": "double precision", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "slos", + "name": "window_days", + "position": 8, + "type": "integer", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "slos", + "name": "alert_rule_id", + "position": 9, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "slos", + "name": "created_by", + "position": 10, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "slos", + "name": "updated_by", + "position": 11, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "slos", + "name": "created_at", + "position": 12, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "slos", + "name": "updated_at", + "position": 13, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "source_map_files", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "source_map_files", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "source_map_files", + "name": "debug_id", + "position": 2, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "source_map_files", + "name": "service_name", + "position": 3, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "source_map_files", + "name": "version", + "position": 4, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "source_map_files", + "name": "minified_path", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "source_map_files", + "name": "size_bytes", + "position": 6, + "type": "integer", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "source_map_files", + "name": "has_sources_content", + "position": 7, + "type": "boolean", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "source_map_files", + "name": "object_key", + "position": 8, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "source_map_files", + "name": "created_at", + "position": 9, + "type": "timestamp with time zone", + "notNull": true, + "default": "now()", + "identity": null + }, + { + "kind": "column", + "table": "source_map_files", + "name": "last_used_at", + "position": 10, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "sources", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "sources", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "sources", + "name": "name", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "sources", + "name": "description", + "position": 3, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "sources", + "name": "platform", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "sources", + "name": "kind", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "sources", + "name": "key_hash", + "position": 6, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "sources", + "name": "key_prefix", + "position": 7, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "sources", + "name": "allowed_signals", + "position": 8, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "sources", + "name": "rate_limit_rps", + "position": 9, + "type": "integer", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "sources", + "name": "resource_attributes", + "position": 10, + "type": "jsonb", + "notNull": true, + "default": "'[]'::jsonb", + "identity": null + }, + { + "kind": "column", + "table": "sources", + "name": "expires_at", + "position": 11, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "sources", + "name": "paused_at", + "position": 12, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "sources", + "name": "paused_until", + "position": 13, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "sources", + "name": "last_used_at", + "position": 14, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "sources", + "name": "last_rejected_at", + "position": 15, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "sources", + "name": "last_rejection", + "position": 16, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "sources", + "name": "last_poll_at", + "position": 17, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "sources", + "name": "last_poll_ok_at", + "position": 18, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "sources", + "name": "last_poll_error", + "position": 19, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "sources", + "name": "disconnected_at", + "position": 20, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "sources", + "name": "poll_resources", + "position": 21, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "sources", + "name": "rolled_at", + "position": 22, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "sources", + "name": "created_at", + "position": 23, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "sources", + "name": "updated_at", + "position": 24, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "sources", + "name": "created_by", + "position": 25, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "sources", + "name": "updated_by", + "position": 26, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_cleanups", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_cleanups", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_cleanups", + "name": "page_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_cleanups", + "name": "slug", + "position": 3, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_cleanups", + "name": "delete_snapshot", + "position": 4, + "type": "boolean", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_cleanups", + "name": "hostname", + "position": 5, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_cleanups", + "name": "cloudflare_hostname_id", + "position": 6, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_cleanups", + "name": "cloudflare_route_id", + "position": 7, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_cleanups", + "name": "created_at", + "position": 8, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_components", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_components", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_components", + "name": "page_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_components", + "name": "name", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_components", + "name": "description", + "position": 4, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_components", + "name": "group_name", + "position": 5, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_components", + "name": "position", + "position": 6, + "type": "integer", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "status_page_components", + "name": "monitor_id", + "position": 7, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_components", + "name": "manual_status", + "position": 8, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_components", + "name": "show_uptime", + "position": 9, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "status_page_components", + "name": "created_at", + "position": 10, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_components", + "name": "updated_at", + "position": 11, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_custom_domains", + "name": "page_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_custom_domains", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_custom_domains", + "name": "hostname", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_custom_domains", + "name": "status", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_custom_domains", + "name": "cloudflare_hostname_id", + "position": 4, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_custom_domains", + "name": "cloudflare_route_id", + "position": 5, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_custom_domains", + "name": "dns_records", + "position": 6, + "type": "jsonb", + "notNull": true, + "default": "'[]'", + "identity": null + }, + { + "kind": "column", + "table": "status_page_custom_domains", + "name": "last_error", + "position": 7, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_custom_domains", + "name": "last_checked_at", + "position": 8, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_custom_domains", + "name": "activated_at", + "position": 9, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_custom_domains", + "name": "created_at", + "position": 10, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_custom_domains", + "name": "updated_at", + "position": 11, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_incident_components", + "name": "incident_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_incident_components", + "name": "component_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_incident_components", + "name": "org_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_incident_updates", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_incident_updates", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_incident_updates", + "name": "incident_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_incident_updates", + "name": "status", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_incident_updates", + "name": "body", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_incident_updates", + "name": "source", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_incident_updates", + "name": "created_by", + "position": 6, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_incident_updates", + "name": "overlay_entry_id", + "position": 7, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_incident_updates", + "name": "created_at", + "position": 8, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_incidents", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_incidents", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_incidents", + "name": "page_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_incidents", + "name": "kind", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_incidents", + "name": "title", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_incidents", + "name": "impact", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_incidents", + "name": "status", + "position": 6, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_incidents", + "name": "published", + "position": 7, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "status_page_incidents", + "name": "alert_incident_id", + "position": 8, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_incidents", + "name": "scheduled_start", + "position": 9, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_incidents", + "name": "scheduled_end", + "position": 10, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_incidents", + "name": "auto_complete", + "position": 11, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "status_page_incidents", + "name": "started_at", + "position": 12, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_incidents", + "name": "resolved_at", + "position": 13, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_incidents", + "name": "created_by", + "position": 14, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_incidents", + "name": "created_at", + "position": 15, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_page_incidents", + "name": "updated_at", + "position": 16, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_pages", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_pages", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_pages", + "name": "name", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_pages", + "name": "slug", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_pages", + "name": "legacy_slug_route", + "position": 4, + "type": "boolean", + "notNull": true, + "default": "false", + "identity": null + }, + { + "kind": "column", + "table": "status_pages", + "name": "description", + "position": 5, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_pages", + "name": "website_url", + "position": 6, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_pages", + "name": "logo_url", + "position": 7, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_pages", + "name": "logo_dark_url", + "position": 8, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_pages", + "name": "favicon_url", + "position": 9, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_pages", + "name": "support_url", + "position": 10, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_pages", + "name": "privacy_url", + "position": 11, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_pages", + "name": "terms_url", + "position": 12, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_pages", + "name": "theme", + "position": 13, + "type": "jsonb", + "notNull": true, + "default": "'{\"preset\":\"default\",\"appearance\":\"auto\",\"accent\":null,\"background\":null,\"text\":null,\"card\":null,\"border\":null,\"radius\":\"md\",\"font\":\"sans\"}'", + "identity": null + }, + { + "kind": "column", + "table": "status_pages", + "name": "show_powered_by", + "position": 14, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "status_pages", + "name": "auto_incidents", + "position": 15, + "type": "text", + "notNull": true, + "default": "'off'", + "identity": null + }, + { + "kind": "column", + "table": "status_pages", + "name": "break_glass_token_sha256", + "position": 16, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_pages", + "name": "break_glass_token_suffix", + "position": 17, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_pages", + "name": "visibility", + "position": 18, + "type": "text", + "notNull": true, + "default": "'public'", + "identity": null + }, + { + "kind": "column", + "table": "status_pages", + "name": "password_hash", + "position": 19, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_pages", + "name": "draft", + "position": 20, + "type": "boolean", + "notNull": true, + "default": "false", + "identity": null + }, + { + "kind": "column", + "table": "status_pages", + "name": "revision", + "position": 21, + "type": "bigint", + "notNull": true, + "default": "1", + "identity": null + }, + { + "kind": "column", + "table": "status_pages", + "name": "published_revision", + "position": 22, + "type": "bigint", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "status_pages", + "name": "published_at", + "position": 23, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_pages", + "name": "last_publish_error", + "position": 24, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_pages", + "name": "published_hash", + "position": 25, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_pages", + "name": "publish_attempted_at", + "position": 26, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_pages", + "name": "created_by", + "position": 27, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_pages", + "name": "created_at", + "position": 28, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "status_pages", + "name": "updated_at", + "position": 29, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "supabase_connections", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "supabase_connections", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "supabase_connections", + "name": "source_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "supabase_connections", + "name": "supabase_organization_id", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "supabase_connections", + "name": "supabase_organization_slug", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "supabase_connections", + "name": "supabase_organization_name", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "supabase_connections", + "name": "connected_by_user_id", + "position": 6, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "supabase_connections", + "name": "discovery_lease_until", + "position": 7, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "supabase_connections", + "name": "last_discovery_at", + "position": 8, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "supabase_connections", + "name": "last_discovery_error", + "position": 9, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "supabase_connections", + "name": "created_at", + "position": 10, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "supabase_connections", + "name": "updated_at", + "position": 11, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "supabase_project_insights", + "name": "project_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "supabase_project_insights", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "supabase_project_insights", + "name": "advisors_json", + "position": 2, + "type": "jsonb", + "notNull": true, + "default": "'[]'", + "identity": null + }, + { + "kind": "column", + "table": "supabase_project_insights", + "name": "top_queries_json", + "position": 3, + "type": "jsonb", + "notNull": true, + "default": "'[]'", + "identity": null + }, + { + "kind": "column", + "table": "supabase_project_insights", + "name": "advisors_checked_at", + "position": 4, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "supabase_project_insights", + "name": "queries_checked_at", + "position": 5, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "supabase_project_insights", + "name": "advisors_error", + "position": 6, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "supabase_project_insights", + "name": "queries_error", + "position": 7, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "supabase_project_insights", + "name": "lease_until", + "position": 8, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "supabase_project_insights", + "name": "hold_until", + "position": 9, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "supabase_project_insights", + "name": "created_at", + "position": 10, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "supabase_project_insights", + "name": "updated_at", + "position": 11, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "supabase_projects", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "supabase_projects", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "supabase_projects", + "name": "connection_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "supabase_projects", + "name": "project_ref", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "supabase_projects", + "name": "name", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "supabase_projects", + "name": "region", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "supabase_projects", + "name": "status", + "position": 6, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "supabase_projects", + "name": "metrics_enabled", + "position": 7, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "supabase_projects", + "name": "scrape_target_id", + "position": 8, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "supabase_projects", + "name": "log_drain_enabled", + "position": 9, + "type": "boolean", + "notNull": true, + "default": "false", + "identity": null + }, + { + "kind": "column", + "table": "supabase_projects", + "name": "log_drain_id", + "position": 10, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "supabase_projects", + "name": "log_drain_source_id", + "position": 11, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "supabase_projects", + "name": "log_drain_error", + "position": 12, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "supabase_projects", + "name": "log_drains_json", + "position": 13, + "type": "jsonb", + "notNull": true, + "default": "'[]'", + "identity": null + }, + { + "kind": "column", + "table": "supabase_projects", + "name": "log_drains_checked_at", + "position": 14, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "supabase_projects", + "name": "logs_enabled", + "position": 15, + "type": "boolean", + "notNull": true, + "default": "false", + "identity": null + }, + { + "kind": "column", + "table": "supabase_projects", + "name": "logs_watermark_at", + "position": 16, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "supabase_projects", + "name": "logs_boundary_ids", + "position": 17, + "type": "jsonb", + "notNull": true, + "default": "'[]'", + "identity": null + }, + { + "kind": "column", + "table": "supabase_projects", + "name": "logs_lease_until", + "position": 18, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "supabase_projects", + "name": "logs_hold_until", + "position": 19, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "supabase_projects", + "name": "logs_last_polled_at", + "position": 20, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "supabase_projects", + "name": "logs_error", + "position": 21, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "supabase_projects", + "name": "last_seen_at", + "position": 22, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "supabase_projects", + "name": "removed_at", + "position": 23, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "supabase_projects", + "name": "created_at", + "position": 24, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "supabase_projects", + "name": "updated_at", + "position": 25, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "uptime_monitor_daily", + "name": "monitor_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "uptime_monitor_daily", + "name": "day", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "uptime_monitor_daily", + "name": "org_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "uptime_monitor_daily", + "name": "checks", + "position": 3, + "type": "integer", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "uptime_monitor_daily", + "name": "failures", + "position": 4, + "type": "integer", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "uptime_monitor_daily", + "name": "down_checks", + "position": 5, + "type": "integer", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "uptime_monitor_daily", + "name": "last_check_at", + "position": 6, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "uptime_monitor_states", + "name": "monitor_id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "uptime_monitor_states", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "uptime_monitor_states", + "name": "status", + "position": 2, + "type": "text", + "notNull": true, + "default": "'pending'", + "identity": null + }, + { + "kind": "column", + "table": "uptime_monitor_states", + "name": "consecutive_failures", + "position": 3, + "type": "integer", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "uptime_monitor_states", + "name": "consecutive_successes", + "position": 4, + "type": "integer", + "notNull": true, + "default": "0", + "identity": null + }, + { + "kind": "column", + "table": "uptime_monitor_states", + "name": "status_changed_at", + "position": 5, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "uptime_monitor_states", + "name": "last_check_json", + "position": 6, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "uptime_monitor_states", + "name": "recent_json", + "position": 7, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "uptime_monitor_states", + "name": "last_ping_at", + "position": 8, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "uptime_monitor_states", + "name": "updated_at", + "position": 9, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "uptime_monitors", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "uptime_monitors", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "uptime_monitors", + "name": "name", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "uptime_monitors", + "name": "kind", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "uptime_monitors", + "name": "config_json", + "position": 4, + "type": "jsonb", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "uptime_monitors", + "name": "headers_ciphertext", + "position": 5, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "uptime_monitors", + "name": "headers_iv", + "position": 6, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "uptime_monitors", + "name": "headers_tag", + "position": 7, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "uptime_monitors", + "name": "interval_seconds", + "position": 8, + "type": "integer", + "notNull": true, + "default": "60", + "identity": null + }, + { + "kind": "column", + "table": "uptime_monitors", + "name": "failures_to_down", + "position": 9, + "type": "integer", + "notNull": true, + "default": "2", + "identity": null + }, + { + "kind": "column", + "table": "uptime_monitors", + "name": "service_name", + "position": 10, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "uptime_monitors", + "name": "alert_rule_id", + "position": 11, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "uptime_monitors", + "name": "heartbeat_token", + "position": 12, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "uptime_monitors", + "name": "enabled", + "position": 13, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "uptime_monitors", + "name": "created_by", + "position": 14, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "uptime_monitors", + "name": "created_at", + "position": 15, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "uptime_monitors", + "name": "updated_at", + "position": 16, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_commits", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_commits", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_commits", + "name": "provider", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_commits", + "name": "repository_id", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_commits", + "name": "sha", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_commits", + "name": "message", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_commits", + "name": "author_name", + "position": 6, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_commits", + "name": "author_email", + "position": 7, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_commits", + "name": "author_login", + "position": 8, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_commits", + "name": "author_avatar_url", + "position": 9, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_commits", + "name": "authored_at", + "position": 10, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_commits", + "name": "committed_at", + "position": 11, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_commits", + "name": "html_url", + "position": 12, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_commits", + "name": "created_at", + "position": 13, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_installations", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_installations", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_installations", + "name": "source_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_installations", + "name": "provider", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_installations", + "name": "external_installation_id", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_installations", + "name": "account_login", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_installations", + "name": "account_type", + "position": 6, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_installations", + "name": "external_account_id", + "position": 7, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_installations", + "name": "account_avatar_url", + "position": 8, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_installations", + "name": "repository_selection", + "position": 9, + "type": "text", + "notNull": true, + "default": "'all'", + "identity": null + }, + { + "kind": "column", + "table": "vcs_installations", + "name": "status", + "position": 10, + "type": "text", + "notNull": true, + "default": "'active'", + "identity": null + }, + { + "kind": "column", + "table": "vcs_installations", + "name": "suspended_at", + "position": 11, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_installations", + "name": "ci_traces_enabled", + "position": 12, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "vcs_installations", + "name": "audit_log_enabled", + "position": 13, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "vcs_installations", + "name": "audit_categories", + "position": 14, + "type": "jsonb", + "notNull": true, + "default": "'{}'", + "identity": null + }, + { + "kind": "column", + "table": "vcs_installations", + "name": "repository_discovery", + "position": 15, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_installations", + "name": "installed_by_user_id", + "position": 16, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_installations", + "name": "created_at", + "position": 17, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_installations", + "name": "updated_at", + "position": 18, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_repositories", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_repositories", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_repositories", + "name": "provider", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_repositories", + "name": "installation_id", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_repositories", + "name": "external_repo_id", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_repositories", + "name": "owner", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_repositories", + "name": "name", + "position": 6, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_repositories", + "name": "full_name", + "position": 7, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_repositories", + "name": "default_branch", + "position": 8, + "type": "text", + "notNull": true, + "default": "'main'", + "identity": null + }, + { + "kind": "column", + "table": "vcs_repositories", + "name": "tracked_branch", + "position": 9, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_repositories", + "name": "html_url", + "position": 10, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_repositories", + "name": "is_private", + "position": 11, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "vcs_repositories", + "name": "is_archived", + "position": 12, + "type": "boolean", + "notNull": true, + "default": "false", + "identity": null + }, + { + "kind": "column", + "table": "vcs_repositories", + "name": "status", + "position": 13, + "type": "text", + "notNull": true, + "default": "'active'", + "identity": null + }, + { + "kind": "column", + "table": "vcs_repositories", + "name": "sync_status", + "position": 14, + "type": "text", + "notNull": true, + "default": "'pending'", + "identity": null + }, + { + "kind": "column", + "table": "vcs_repositories", + "name": "last_synced_at", + "position": 15, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_repositories", + "name": "last_sync_error", + "position": 16, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_repositories", + "name": "pr_review_enabled", + "position": 17, + "type": "boolean", + "notNull": true, + "default": "false", + "identity": null + }, + { + "kind": "column", + "table": "vcs_repositories", + "name": "pr_review_config", + "position": 18, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_repositories", + "name": "created_at", + "position": 19, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_repositories", + "name": "updated_at", + "position": 20, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_repository_branches", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_repository_branches", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_repository_branches", + "name": "provider", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_repository_branches", + "name": "repository_id", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_repository_branches", + "name": "name", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_repository_branches", + "name": "is_default", + "position": 5, + "type": "boolean", + "notNull": true, + "default": "false", + "identity": null + }, + { + "kind": "column", + "table": "vcs_repository_branches", + "name": "head_sha", + "position": 6, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_repository_branches", + "name": "created_at", + "position": 7, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vcs_repository_branches", + "name": "updated_at", + "position": 8, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_connections", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_connections", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_connections", + "name": "source_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_connections", + "name": "team_id", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_connections", + "name": "team_slug", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_connections", + "name": "team_name", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_connections", + "name": "token_ciphertext", + "position": 6, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_connections", + "name": "token_iv", + "position": 7, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_connections", + "name": "token_tag", + "position": 8, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_connections", + "name": "connected_by_user_id", + "position": 9, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_connections", + "name": "project_scope", + "position": 10, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_connections", + "name": "project_ids", + "position": 11, + "type": "jsonb", + "notNull": true, + "default": "'[]'", + "identity": null + }, + { + "kind": "column", + "table": "vercel_connections", + "name": "sampling_rate", + "position": 12, + "type": "double precision", + "notNull": true, + "default": "1", + "identity": null + }, + { + "kind": "column", + "table": "vercel_connections", + "name": "logs_enabled", + "position": 13, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "vercel_connections", + "name": "traces_enabled", + "position": 14, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "vercel_connections", + "name": "ai_gateway_enabled", + "position": 15, + "type": "boolean", + "notNull": true, + "default": "true", + "identity": null + }, + { + "kind": "column", + "table": "vercel_connections", + "name": "speed_insights_enabled", + "position": 16, + "type": "boolean", + "notNull": true, + "default": "false", + "identity": null + }, + { + "kind": "column", + "table": "vercel_connections", + "name": "web_analytics_enabled", + "position": 17, + "type": "boolean", + "notNull": true, + "default": "false", + "identity": null + }, + { + "kind": "column", + "table": "vercel_connections", + "name": "audit_log_enabled", + "position": 18, + "type": "boolean", + "notNull": true, + "default": "false", + "identity": null + }, + { + "kind": "column", + "table": "vercel_connections", + "name": "log_drain_id", + "position": 19, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_connections", + "name": "trace_drain_id", + "position": 20, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_connections", + "name": "ai_gateway_drain_id", + "position": 21, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_connections", + "name": "speed_insights_drain_id", + "position": 22, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_connections", + "name": "web_analytics_drain_id", + "position": 23, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_connections", + "name": "audit_log_drain_id", + "position": 24, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_connections", + "name": "log_drain_state", + "position": 25, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_connections", + "name": "trace_drain_state", + "position": 26, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_connections", + "name": "ai_gateway_drain_state", + "position": 27, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_connections", + "name": "speed_insights_drain_state", + "position": 28, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_connections", + "name": "web_analytics_drain_state", + "position": 29, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_connections", + "name": "audit_log_drain_state", + "position": 30, + "type": "jsonb", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_connections", + "name": "drain_key_hash", + "position": 31, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_connections", + "name": "auth_failed_at", + "position": 32, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_connections", + "name": "discovered_at", + "position": 33, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_connections", + "name": "deployments_watermark_at", + "position": 34, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_connections", + "name": "lease_until", + "position": 35, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_connections", + "name": "hold_until", + "position": 36, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_connections", + "name": "last_success_at", + "position": 37, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_connections", + "name": "last_error", + "position": 38, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_connections", + "name": "last_error_at", + "position": 39, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_connections", + "name": "created_at", + "position": 40, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_connections", + "name": "updated_at", + "position": 41, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_deployments", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_deployments", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_deployments", + "name": "connection_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_deployments", + "name": "project_id", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_deployments", + "name": "deployment_id", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_deployments", + "name": "url", + "position": 5, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_deployments", + "name": "target", + "position": 6, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_deployments", + "name": "state", + "position": 7, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_deployments", + "name": "branch", + "position": 8, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_deployments", + "name": "commit_sha", + "position": 9, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_deployments", + "name": "commit_message", + "position": 10, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_deployments", + "name": "creator", + "position": 11, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_deployments", + "name": "error_code", + "position": 12, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_deployments", + "name": "error_message", + "position": 13, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_deployments", + "name": "created_at_vercel", + "position": 14, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_deployments", + "name": "building_at", + "position": 15, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_deployments", + "name": "ready_at", + "position": 16, + "type": "timestamp with time zone", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_deployments", + "name": "inspector_url", + "position": 17, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_deployments", + "name": "updated_at", + "position": 18, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_projects", + "name": "id", + "position": 0, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_projects", + "name": "org_id", + "position": 1, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_projects", + "name": "connection_id", + "position": 2, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_projects", + "name": "project_id", + "position": 3, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_projects", + "name": "name", + "position": 4, + "type": "text", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_projects", + "name": "framework", + "position": 5, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_projects", + "name": "production_deployment_id", + "position": 6, + "type": "text", + "notNull": false, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_projects", + "name": "created_at", + "position": 7, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "column", + "table": "vercel_projects", + "name": "updated_at", + "position": 8, + "type": "timestamp with time zone", + "notNull": true, + "default": null, + "identity": null + }, + { + "kind": "index", + "table": "actors", + "name": "actors_org_agent_name_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"agent_name\"" + ], + "where": null + }, + { + "kind": "index", + "table": "actors", + "name": "actors_org_type_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"type\"" + ], + "where": null + }, + { + "kind": "index", + "table": "actors", + "name": "actors_org_user_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"user_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "agent_feedback", + "name": "agent_feedback_kind_created_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"kind\"", + "\"created_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "agent_feedback", + "name": "agent_feedback_org_created_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"created_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "alert_delivery_events", + "name": "alert_delivery_events_claim_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"status\"", + "\"claim_expires_at\"", + "\"scheduled_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "alert_delivery_events", + "name": "alert_delivery_events_delivery_attempt_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"delivery_key\"", + "\"attempt_number\"" + ], + "where": null + }, + { + "kind": "index", + "table": "alert_delivery_events", + "name": "alert_delivery_events_due_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"status\"", + "\"scheduled_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "alert_delivery_events", + "name": "alert_delivery_events_org_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "alert_delivery_events", + "name": "alert_delivery_events_org_incident_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"incident_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "alert_destinations", + "name": "alert_destinations_org_enabled_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"enabled\"" + ], + "where": null + }, + { + "kind": "index", + "table": "alert_destinations", + "name": "alert_destinations_org_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "alert_destinations", + "name": "alert_destinations_org_name_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"name\"" + ], + "where": null + }, + { + "kind": "index", + "table": "alert_escalation_runs", + "name": "alert_escalation_runs_live_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"status\"", + "\"next_step_at\"" + ], + "where": "\"status\" in ('active', 'acknowledged')" + }, + { + "kind": "index", + "table": "alert_escalation_runs", + "name": "alert_escalation_runs_live_incident_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"incident_id\"" + ], + "where": "\"status\" IN ('active', 'acknowledged')" + }, + { + "kind": "index", + "table": "alert_escalation_runs", + "name": "alert_escalation_runs_org_incident_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"incident_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "alert_incident_events", + "name": "alert_incident_events_incident_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"incident_id\"", + "\"created_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "alert_incidents", + "name": "alert_incidents_incident_key_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"incident_key\"" + ], + "where": null + }, + { + "kind": "index", + "table": "alert_incidents", + "name": "alert_incidents_open_group_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"rule_id\"", + "\"group_key\"" + ], + "where": "\"status\" = 'open'" + }, + { + "kind": "index", + "table": "alert_incidents", + "name": "alert_incidents_org_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "alert_incidents", + "name": "alert_incidents_org_issue_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"error_issue_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "alert_incidents", + "name": "alert_incidents_org_rule_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"rule_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "alert_incidents", + "name": "alert_incidents_org_status_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"status\"" + ], + "where": null + }, + { + "kind": "index", + "table": "alert_incidents", + "name": "alert_incidents_quiet_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"rule_id\"" + ], + "where": "\"quiet_since\" IS NOT NULL" + }, + { + "kind": "index", + "table": "alert_linear_issues", + "name": "alert_linear_issues_org_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "alert_linear_issues", + "name": "alert_linear_issues_thread_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"destination_id\"", + "\"thread_key\"" + ], + "where": null + }, + { + "kind": "index", + "table": "alert_maintenance_windows", + "name": "alert_maintenance_windows_enabled_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"enabled\"", + "\"id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "alert_maintenance_windows", + "name": "alert_maintenance_windows_org_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "alert_member_notifications", + "name": "alert_member_notifications_dedupe_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"dedupe_key\"" + ], + "where": null + }, + { + "kind": "index", + "table": "alert_member_notifications", + "name": "alert_member_notifications_due_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"status\"", + "\"scheduled_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "alert_member_notifications", + "name": "alert_member_notifications_org_incident_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"incident_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "alert_rule_claims", + "name": "alert_rule_claims_org_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "alert_rule_states", + "name": "alert_rule_states_org_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "alert_rules", + "name": "alert_rules_org_enabled_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"enabled\"" + ], + "where": null + }, + { + "kind": "index", + "table": "alert_rules", + "name": "alert_rules_org_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "alert_rules", + "name": "alert_rules_org_name_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"name\"" + ], + "where": null + }, + { + "kind": "index", + "table": "alert_silences", + "name": "alert_silences_maintenance_occurrence_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"maintenance_window_id\"", + "\"starts_at\"" + ], + "where": "\"maintenance_window_id\" IS NOT NULL" + }, + { + "kind": "index", + "table": "alert_silences", + "name": "alert_silences_org_ends_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"ends_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "anomaly_detector_states", + "name": "anomaly_detector_states_evaluated_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"last_evaluated_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "anomaly_detector_states", + "name": "anomaly_detector_states_open_incident_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"open_incident_id\"" + ], + "where": "\"open_incident_id\" is not null" + }, + { + "kind": "index", + "table": "anomaly_incidents", + "name": "anomaly_incidents_open_detector_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"detector_key\"" + ], + "where": "\"status\" = 'open'" + }, + { + "kind": "index", + "table": "anomaly_incidents", + "name": "anomaly_incidents_org_detector_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"detector_key\"" + ], + "where": null + }, + { + "kind": "index", + "table": "anomaly_incidents", + "name": "anomaly_incidents_org_issue_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"error_issue_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "anomaly_incidents", + "name": "anomaly_incidents_org_status_triggered_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"status\"", + "\"last_triggered_at\"", + "\"id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "anomaly_incidents", + "name": "anomaly_incidents_org_triggered_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"last_triggered_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "api_keys", + "name": "api_keys_key_hash_unique", + "unique": true, + "method": "btree", + "columns": [ + "\"key_hash\"" + ], + "where": null + }, + { + "kind": "index", + "table": "api_keys", + "name": "api_keys_org_id_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "aws_connections", + "name": "aws_connections_org_account_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"account_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "aws_connections", + "name": "aws_connections_org_id_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "aws_connections", + "name": "aws_connections_source_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"source_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "aws_connections", + "name": "aws_connections_stream_secret_hash_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"stream_secret_hash\"" + ], + "where": null + }, + { + "kind": "index", + "table": "cancellation_reviews", + "name": "cancellation_reviews_subscription_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"plan_id\"", + "\"subscription_started_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "chat_identities", + "name": "chat_identities_org_connector_external_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"connector\"", + "\"external_user_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "chat_identities", + "name": "chat_identities_org_connector_user_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"connector\"", + "\"user_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "chat_identities", + "name": "chat_identities_org_user_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"user_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "chat_workspaces", + "name": "chat_workspaces_connector_external_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"connector\"", + "\"external_workspace_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "chat_workspaces", + "name": "chat_workspaces_org_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "cli_device_authorizations", + "name": "cli_device_authorizations_expires_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"expires_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "cli_device_authorizations", + "name": "cli_device_authorizations_user_code_unique", + "unique": true, + "method": "btree", + "columns": [ + "\"user_code_hash\"" + ], + "where": null + }, + { + "kind": "index", + "table": "cloud_security_findings", + "name": "cloud_security_findings_org_resource_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"resource_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "cloud_security_findings", + "name": "cloud_security_findings_org_status_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"status\"", + "\"last_seen_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "cloud_security_service_states", + "name": "cloud_security_service_states_org_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "cloudflare_analytics_state", + "name": "cf_analytics_state_org_account_dataset_zone_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"account_id\"", + "\"dataset\"", + "\"zone_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "cloudflare_analytics_state", + "name": "cf_analytics_state_org_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "cloudflare_hyperdrive_configs", + "name": "cloudflare_hyperdrive_configs_org_config_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"config_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "cloudflare_hyperdrive_configs", + "name": "cloudflare_hyperdrive_configs_org_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "cloudflare_logpush_connectors", + "name": "cloudflare_logpush_connectors_org_enabled_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"enabled\"" + ], + "where": null + }, + { + "kind": "index", + "table": "cloudflare_logpush_connectors", + "name": "cloudflare_logpush_connectors_org_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "cloudflare_logpush_connectors", + "name": "cloudflare_logpush_connectors_secret_hash_unique", + "unique": true, + "method": "btree", + "columns": [ + "\"secret_hash\"" + ], + "where": null + }, + { + "kind": "index", + "table": "cloudflare_logpush_connectors", + "name": "cloudflare_logpush_connectors_source_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"source_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "cookieless_visits", + "name": "cookieless_visits_last_seen_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"last_seen_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "cost_connections", + "name": "cost_connections_org_provider_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"provider\"" + ], + "where": null + }, + { + "kind": "index", + "table": "cost_sources", + "name": "cost_sources_org_provider_ref_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"provider\"", + "\"connection_ref\"" + ], + "where": null + }, + { + "kind": "index", + "table": "dashboard_shares", + "name": "dashboard_shares_id_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "dashboard_shares", + "name": "dashboard_shares_live_unq", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"dashboard_id\"", + "coalesce(widget_id, '')" + ], + "where": "revoked_at is null" + }, + { + "kind": "index", + "table": "dashboard_shares", + "name": "dashboard_shares_org_dashboard_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"dashboard_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "dashboard_shares", + "name": "dashboard_shares_token_hash_unq", + "unique": true, + "method": "btree", + "columns": [ + "\"token_hash\"" + ], + "where": null + }, + { + "kind": "index", + "table": "dashboard_versions", + "name": "dashboard_versions_org_dashboard_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"dashboard_id\"", + "\"version_number\"" + ], + "where": null + }, + { + "kind": "index", + "table": "dashboard_versions", + "name": "dashboard_versions_org_dashboard_version_unq", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"dashboard_id\"", + "\"version_number\"" + ], + "where": null + }, + { + "kind": "index", + "table": "dashboards", + "name": "dashboards_org_name_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"name\"" + ], + "where": null + }, + { + "kind": "index", + "table": "dashboards", + "name": "dashboards_org_updated_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"updated_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "dependency_findings", + "name": "dependency_findings_key_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"repository_id\"", + "\"lockfile_path\"", + "\"ecosystem\"", + "\"package_name\"", + "\"advisory_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "dependency_findings", + "name": "dependency_findings_org_status_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"status\"" + ], + "where": null + }, + { + "kind": "index", + "table": "dependency_findings", + "name": "dependency_findings_org_updated_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"updated_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "dependency_scan_matches", + "name": "dependency_scan_matches_org_scan_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"scan_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "dependency_scans", + "name": "dependency_scans_org_started_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"started_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "dependency_scans", + "name": "dependency_scans_repo_commit_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"repository_id\"", + "\"commit_sha\"" + ], + "where": null + }, + { + "kind": "index", + "table": "dependency_scans", + "name": "dependency_scans_repo_started_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"repository_id\"", + "\"started_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "device_credentials", + "name": "device_credentials_jkt_unique", + "unique": true, + "method": "btree", + "columns": [ + "\"jkt\"" + ], + "where": null + }, + { + "kind": "index", + "table": "device_credentials", + "name": "device_credentials_live_installation_unique", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"installation_id\"" + ], + "where": "\"revoked_at\" IS NULL" + }, + { + "kind": "index", + "table": "device_credentials", + "name": "device_credentials_user_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"user_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "device_proof_replays", + "name": "device_proof_replays_expires_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"expires_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "digest_subscriptions", + "name": "digest_subscriptions_org_enabled_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"enabled\"" + ], + "where": null + }, + { + "kind": "index", + "table": "digest_subscriptions", + "name": "digest_subscriptions_org_user_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"user_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "error_fingerprint_candidates", + "name": "error_fingerprint_candidates_last_seen_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"last_seen_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "error_grouping_keys", + "name": "error_grouping_keys_key_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"grouping_key\"" + ], + "where": null + }, + { + "kind": "index", + "table": "error_incidents", + "name": "error_incidents_org_issue_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"issue_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "error_incidents", + "name": "error_incidents_org_status_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"status\"", + "\"last_triggered_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "error_issue_events", + "name": "error_issue_events_actor_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"actor_id\"", + "\"created_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "error_issue_events", + "name": "error_issue_events_issue_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"issue_id\"", + "\"created_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "error_issue_events", + "name": "error_issue_events_type_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"type\"", + "\"created_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "error_issue_fingerprints", + "name": "error_issue_fingerprints_issue_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"issue_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "error_issue_pull_requests", + "name": "error_issue_pull_requests_issue_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"issue_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "error_issue_pull_requests", + "name": "error_issue_pull_requests_issue_pr_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"issue_id\"", + "\"provider\"", + "\"repo_full_name\"", + "\"number\"" + ], + "where": null + }, + { + "kind": "index", + "table": "error_issue_pull_requests", + "name": "error_issue_pull_requests_repo_number_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"provider\"", + "\"repo_full_name\"", + "\"number\"" + ], + "where": null + }, + { + "kind": "index", + "table": "error_issue_verifications", + "name": "error_issue_verifications_due_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"status\"", + "\"verify_after\"" + ], + "where": null + }, + { + "kind": "index", + "table": "error_issue_verifications", + "name": "error_issue_verifications_issue_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"issue_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "error_issue_verifications", + "name": "error_issue_verifications_open_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"issue_id\"" + ], + "where": "\"status\" in ('waiting', 'running')" + }, + { + "kind": "index", + "table": "error_issues", + "name": "error_issues_lease_expiry_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"lease_expires_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "error_issues", + "name": "error_issues_org_archived_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"archived_at\"" + ], + "where": "\"archived_at\" is not null" + }, + { + "kind": "index", + "table": "error_issues", + "name": "error_issues_org_assignee_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"assigned_actor_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "error_issues", + "name": "error_issues_org_fp_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"fingerprint_hash\"" + ], + "where": null + }, + { + "kind": "index", + "table": "error_issues", + "name": "error_issues_org_fp_version_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"fingerprint_version\"" + ], + "where": null + }, + { + "kind": "index", + "table": "error_issues", + "name": "error_issues_org_kind_created_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"kind\"", + "\"created_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "error_issues", + "name": "error_issues_org_live_seen_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"last_seen_at\"", + "\"id\"" + ], + "where": "\"archived_at\" is null" + }, + { + "kind": "index", + "table": "error_issues", + "name": "error_issues_org_merged_into_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"merged_into_issue_id\"" + ], + "where": "\"merged_into_issue_id\" is not null" + }, + { + "kind": "index", + "table": "error_issues", + "name": "error_issues_org_severity_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"severity\"" + ], + "where": null + }, + { + "kind": "index", + "table": "error_issues", + "name": "error_issues_org_workflow_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"workflow_state\"" + ], + "where": null + }, + { + "kind": "index", + "table": "error_notification_deliveries", + "name": "error_notification_deliveries_due_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"status\"", + "\"scheduled_at\"", + "\"claim_expires_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "error_notification_deliveries", + "name": "error_notification_deliveries_key_destination_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"delivery_key\"", + "\"destination_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "error_notification_deliveries", + "name": "error_notification_deliveries_org_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "error_tick_states", + "name": "error_tick_states_claim_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"claim_expires_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "escalation_chains", + "name": "escalation_chains_org_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "external_data_source_catalog_entries", + "name": "external_data_source_catalog_entries_org_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "external_data_sources", + "name": "external_data_sources_org_name_unique", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"name\"" + ], + "where": null + }, + { + "kind": "index", + "table": "feature_requests", + "name": "feature_requests_area_created_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"area\"", + "\"created_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "feature_requests", + "name": "feature_requests_org_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "fleet_connections", + "name": "fleet_connections_org_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "gcp_connectors", + "name": "gcp_connectors_org_scope_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"scope_type\"", + "\"scope_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "gcp_connectors", + "name": "gcp_connectors_secret_hash_unique", + "unique": true, + "method": "btree", + "columns": [ + "\"secret_hash\"" + ], + "where": null + }, + { + "kind": "index", + "table": "gcp_connectors", + "name": "gcp_connectors_source_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"source_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "gcp_cost_exports", + "name": "gcp_cost_exports_connector_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"connector_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "gcp_cost_exports", + "name": "gcp_cost_exports_org_account_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"billing_account_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "investigations", + "name": "investigations_incident_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"incident_kind\"", + "\"incident_id\"" + ], + "where": "\"incident_id\" is not null" + }, + { + "kind": "index", + "table": "investigations", + "name": "investigations_org_created_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"created_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "investigations", + "name": "investigations_org_issue_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"issue_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "investigations", + "name": "investigations_org_status_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"status\"" + ], + "where": null + }, + { + "kind": "index", + "table": "issue_escalations", + "name": "issue_escalations_dedupe_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"dedupe_key\"" + ], + "where": null + }, + { + "kind": "index", + "table": "issue_escalations", + "name": "issue_escalations_due_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"status\"", + "\"created_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "issue_escalations", + "name": "issue_escalations_org_issue_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"issue_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "live_activities", + "name": "live_activities_device_incident_unique", + "unique": true, + "method": "btree", + "columns": [ + "\"device_id\"", + "\"incident_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "live_activities", + "name": "live_activities_incident_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"incident_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "mcp_oauth_authorizations", + "name": "mcp_oauth_authorizations_code_unique", + "unique": true, + "method": "btree", + "columns": [ + "\"authorization_code_hash\"" + ], + "where": null + }, + { + "kind": "index", + "table": "mcp_oauth_authorizations", + "name": "mcp_oauth_authorizations_expires_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"expires_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "mcp_oauth_refresh_tokens", + "name": "mcp_oauth_refresh_tokens_expires_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"expires_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "mcp_oauth_refresh_tokens", + "name": "mcp_oauth_refresh_tokens_family_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"family_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "mcp_oauth_refresh_tokens", + "name": "mcp_oauth_refresh_tokens_hash_unique", + "unique": true, + "method": "btree", + "columns": [ + "\"token_hash\"" + ], + "where": null + }, + { + "kind": "index", + "table": "mobile_devices", + "name": "mobile_devices_org_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "mobile_devices", + "name": "mobile_devices_org_platform_token_unique", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"platform\"", + "\"token\"" + ], + "where": null + }, + { + "kind": "index", + "table": "mobile_devices", + "name": "mobile_devices_user_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"user_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "oauth_auth_states", + "name": "oauth_auth_states_expires_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"expires_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "oauth_connections", + "name": "oauth_connections_org_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "oauth_connections", + "name": "oauth_connections_org_provider_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"provider\"" + ], + "where": null + }, + { + "kind": "index", + "table": "oauth_connections", + "name": "oauth_connections_source_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"source_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "onboarding_agent_runs", + "name": "onboarding_agent_runs_handoff_code_hash_unq", + "unique": true, + "method": "btree", + "columns": [ + "\"handoff_code_hash\"" + ], + "where": null + }, + { + "kind": "index", + "table": "onboarding_agent_runs", + "name": "onboarding_agent_runs_org_api_key_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"api_key_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "onboarding_agent_runs", + "name": "onboarding_agent_runs_org_user_created_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"user_id\"", + "\"created_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "oncall_overrides", + "name": "oncall_overrides_org_schedule_ends_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"schedule_id\"", + "\"ends_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "oncall_schedules", + "name": "oncall_schedules_calendar_feed_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"calendar_feed_token_hash\"" + ], + "where": null + }, + { + "kind": "index", + "table": "oncall_schedules", + "name": "oncall_schedules_org_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "openrouter_cost_connections", + "name": "openrouter_cost_connections_org_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "org_billing_links", + "name": "org_billing_links_billing_org_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"billing_org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "org_directory_groups", + "name": "org_directory_groups_org_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "org_erasures", + "name": "org_erasures_due_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"next_attempt_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "org_erasures", + "name": "org_erasures_target_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"kind\"", + "\"target\"" + ], + "where": null + }, + { + "kind": "index", + "table": "org_ingest_attribute_mappings", + "name": "org_ingest_attribute_mappings_org_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "org_ingest_keys", + "name": "org_ingest_keys_private_key_hash_unique", + "unique": true, + "method": "btree", + "columns": [ + "\"private_key_hash\"" + ], + "where": null + }, + { + "kind": "index", + "table": "org_ingest_keys", + "name": "org_ingest_keys_public_key_hash_unique", + "unique": true, + "method": "btree", + "columns": [ + "\"public_key_hash\"" + ], + "where": null + }, + { + "kind": "index", + "table": "org_ingest_keys", + "name": "org_ingest_keys_public_key_unique", + "unique": true, + "method": "btree", + "columns": [ + "\"public_key\"" + ], + "where": null + }, + { + "kind": "index", + "table": "org_ingest_rule_stats", + "name": "org_ingest_rule_stats_org_bucket_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"bucket\"" + ], + "where": null + }, + { + "kind": "index", + "table": "org_ingest_rules", + "name": "org_ingest_rules_org_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "org_recommendation_issues", + "name": "org_recommendation_issues_org_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "org_recommendation_issues", + "name": "org_recommendation_issues_org_key_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"recommendation_key\"" + ], + "where": null + }, + { + "kind": "index", + "table": "org_sso_connections", + "name": "org_sso_connections_connection_unq", + "unique": true, + "method": "btree", + "columns": [ + "\"clerk_connection_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "org_sso_connections", + "name": "org_sso_connections_directory_unq", + "unique": true, + "method": "btree", + "columns": [ + "\"clerk_directory_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "planetscale_connections", + "name": "planetscale_connections_org_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "planetscale_connections", + "name": "planetscale_connections_source_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"source_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "planetscale_databases", + "name": "planetscale_databases_org_db_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"database_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "planetscale_databases", + "name": "planetscale_databases_org_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "planetscale_events", + "name": "planetscale_events_dedupe_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"database_name\"", + "\"event_type\"", + "\"external_id\"", + "\"occurred_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "planetscale_events", + "name": "planetscale_events_org_db_time_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"database_name\"", + "\"occurred_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "planetscale_events", + "name": "planetscale_events_org_time_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"occurred_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "planetscale_issue_receipts", + "name": "planetscale_issue_receipts_processed_at_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"processed_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "planetscale_poll_state", + "name": "planetscale_poll_state_org_dataset_db_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"dataset\"", + "\"database_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "planetscale_poll_state", + "name": "planetscale_poll_state_org_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "pr_review_edits", + "name": "pr_review_edits_reply_seq_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"reply_id\"", + "\"seq\"" + ], + "where": null + }, + { + "kind": "index", + "table": "pr_review_finding_embeddings", + "name": "pr_review_finding_embeddings_org_model_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"model\"" + ], + "where": null + }, + { + "kind": "index", + "table": "pr_review_findings", + "name": "pr_review_findings_org_created_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"created_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "pr_review_findings", + "name": "pr_review_findings_pr_handle_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"repository_id\"", + "\"number\"", + "\"handle\"" + ], + "where": null + }, + { + "kind": "index", + "table": "pr_review_merge_steps", + "name": "pr_review_merge_steps_org_created_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"created_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "pr_review_merge_steps", + "name": "pr_review_merge_steps_pr_key_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"repository_id\"", + "\"number\"", + "\"key\"" + ], + "where": null + }, + { + "kind": "index", + "table": "pr_review_replies", + "name": "pr_review_replies_org_created_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"created_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "pr_review_replies", + "name": "pr_review_replies_repo_comment_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"repository_id\"", + "\"comment_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "pr_reviews", + "name": "pr_reviews_org_created_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"created_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "pr_reviews", + "name": "pr_reviews_post_merge_due_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"post_merge_after\"" + ], + "where": "\"post_merge_status\" = 'waiting'" + }, + { + "kind": "index", + "table": "pr_reviews", + "name": "pr_reviews_repo_number_head_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"repository_id\"", + "\"number\"", + "\"head_sha\"" + ], + "where": null + }, + { + "kind": "index", + "table": "pr_reviews", + "name": "pr_reviews_repo_number_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"repository_id\"", + "\"number\"" + ], + "where": null + }, + { + "kind": "index", + "table": "railway_connections", + "name": "railway_connections_org_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "railway_connections", + "name": "railway_connections_source_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"source_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "railway_environments", + "name": "railway_environments_connection_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"connection_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "railway_environments", + "name": "railway_environments_org_env_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"environment_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "saved_views", + "name": "saved_views_org_surface_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"surface\"", + "\"visibility\"" + ], + "where": null + }, + { + "kind": "index", + "table": "saved_views", + "name": "saved_views_owner_surface_name_unq", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"owner_user_id\"", + "\"surface\"", + "\"name\"" + ], + "where": null + }, + { + "kind": "index", + "table": "scrape_target_checks", + "name": "scrape_target_checks_target_checked_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"target_id\"", + "\"checked_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "scrape_targets", + "name": "scrape_targets_org_enabled_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"enabled\"" + ], + "where": null + }, + { + "kind": "index", + "table": "scrape_targets", + "name": "scrape_targets_org_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "scrape_targets", + "name": "scrape_targets_source_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"source_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "search_console_sites", + "name": "search_console_sites_connection_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"oauth_connection_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "search_console_sites", + "name": "search_console_sites_org_site_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"site_url\"" + ], + "where": null + }, + { + "kind": "index", + "table": "security_audit_events", + "name": "security_audit_events_run_at_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"run_id\"", + "\"at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "security_audit_findings", + "name": "security_audit_findings_org_created_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"created_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "security_audit_findings", + "name": "security_audit_findings_target_fingerprint_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"target_id\"", + "\"fingerprint\"" + ], + "where": null + }, + { + "kind": "index", + "table": "security_audit_org_reservations", + "name": "security_audit_org_reservations_org_created_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"created_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "security_audit_runs", + "name": "security_audit_runs_one_running_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"target_id\"" + ], + "where": "\"finished_at\" IS NULL" + }, + { + "kind": "index", + "table": "security_audit_runs", + "name": "security_audit_runs_org_started_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"started_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "security_audit_runs", + "name": "security_audit_runs_target_started_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"target_id\"", + "\"started_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "security_audit_targets", + "name": "security_audit_targets_org_created_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"created_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "security_audit_targets", + "name": "security_audit_targets_org_repo_branch_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"repository\"", + "\"branch\"" + ], + "where": null + }, + { + "kind": "index", + "table": "slos", + "name": "slos_org_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "slos", + "name": "slos_org_name_unq", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"name\"" + ], + "where": null + }, + { + "kind": "index", + "table": "source_map_files", + "name": "source_map_files_org_created_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"created_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "source_map_files", + "name": "source_map_files_org_debug_id_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"debug_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "source_map_files", + "name": "source_map_files_org_release_path_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"service_name\"", + "\"version\"", + "\"minified_path\"" + ], + "where": "\"debug_id\" IS NULL" + }, + { + "kind": "index", + "table": "sources", + "name": "sources_key_hash_unique", + "unique": true, + "method": "btree", + "columns": [ + "\"key_hash\"" + ], + "where": null + }, + { + "kind": "index", + "table": "sources", + "name": "sources_org_default_kind_unique", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": "\"kind\" = 'default'" + }, + { + "kind": "index", + "table": "sources", + "name": "sources_org_id_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "status_page_cleanups", + "name": "status_page_cleanups_created_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"created_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "status_page_components", + "name": "status_page_components_monitor_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"monitor_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "status_page_components", + "name": "status_page_components_page_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"page_id\"", + "\"position\"" + ], + "where": null + }, + { + "kind": "index", + "table": "status_page_custom_domains", + "name": "status_page_custom_domains_checked_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"last_checked_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "status_page_custom_domains", + "name": "status_page_custom_domains_hostname_unq", + "unique": true, + "method": "btree", + "columns": [ + "\"hostname\"" + ], + "where": null + }, + { + "kind": "index", + "table": "status_page_custom_domains", + "name": "status_page_custom_domains_org_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "status_page_incident_components", + "name": "status_page_incident_components_component_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"component_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "status_page_incident_updates", + "name": "status_page_incident_updates_incident_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"incident_id\"", + "\"created_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "status_page_incident_updates", + "name": "status_page_incident_updates_overlay_unq", + "unique": true, + "method": "btree", + "columns": [ + "\"overlay_entry_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "status_page_incidents", + "name": "status_page_incidents_alert_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"alert_incident_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "status_page_incidents", + "name": "status_page_incidents_open_maintenance_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"scheduled_start\"" + ], + "where": "\"kind\" = 'maintenance' and \"resolved_at\" is null" + }, + { + "kind": "index", + "table": "status_page_incidents", + "name": "status_page_incidents_page_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"page_id\"", + "\"started_at\"" + ], + "where": null + }, + { + "kind": "index", + "table": "status_pages", + "name": "status_pages_org_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "status_pages", + "name": "status_pages_org_slug_unq", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"slug\"" + ], + "where": null + }, + { + "kind": "index", + "table": "status_pages", + "name": "status_pages_unpublished_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"revision\"", + "\"published_revision\"" + ], + "where": "revision > published_revision" + }, + { + "kind": "index", + "table": "supabase_connections", + "name": "supabase_connections_org_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "supabase_connections", + "name": "supabase_connections_source_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"source_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "supabase_project_insights", + "name": "supabase_project_insights_org_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "supabase_projects", + "name": "supabase_projects_connection_ref_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"connection_id\"", + "\"project_ref\"" + ], + "where": null + }, + { + "kind": "index", + "table": "supabase_projects", + "name": "supabase_projects_log_drain_source_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"log_drain_source_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "supabase_projects", + "name": "supabase_projects_org_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "uptime_monitor_daily", + "name": "uptime_monitor_daily_org_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "uptime_monitor_states", + "name": "uptime_monitor_states_org_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "uptime_monitors", + "name": "uptime_monitors_enabled_kind_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"enabled\"", + "\"kind\"" + ], + "where": null + }, + { + "kind": "index", + "table": "uptime_monitors", + "name": "uptime_monitors_heartbeat_token_unq", + "unique": true, + "method": "btree", + "columns": [ + "\"heartbeat_token\"" + ], + "where": null + }, + { + "kind": "index", + "table": "uptime_monitors", + "name": "uptime_monitors_org_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "vcs_commits", + "name": "vcs_commits_org_sha_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"sha\"" + ], + "where": null + }, + { + "kind": "index", + "table": "vcs_commits", + "name": "vcs_commits_repo_sha_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"repository_id\"", + "\"sha\"" + ], + "where": null + }, + { + "kind": "index", + "table": "vcs_installations", + "name": "vcs_installations_org_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "vcs_installations", + "name": "vcs_installations_provider_external_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"provider\"", + "\"external_installation_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "vcs_installations", + "name": "vcs_installations_source_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"source_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "vcs_repositories", + "name": "vcs_repositories_installation_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"installation_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "vcs_repositories", + "name": "vcs_repositories_org_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "vcs_repositories", + "name": "vcs_repositories_org_repo_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"provider\"", + "\"external_repo_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "vcs_repository_branches", + "name": "vcs_repository_branches_org_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "vcs_repository_branches", + "name": "vcs_repository_branches_repo_name_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"repository_id\"", + "\"name\"" + ], + "where": null + }, + { + "kind": "index", + "table": "vercel_connections", + "name": "vercel_connections_org_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "vercel_connections", + "name": "vercel_connections_source_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"source_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "vercel_deployments", + "name": "vercel_deployments_org_deployment_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"deployment_id\"" + ], + "where": null + }, + { + "kind": "index", + "table": "vercel_deployments", + "name": "vercel_deployments_org_project_created_idx", + "unique": false, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"project_id\"", + "\"created_at_vercel\"" + ], + "where": null + }, + { + "kind": "index", + "table": "vercel_projects", + "name": "vercel_projects_org_project_idx", + "unique": true, + "method": "btree", + "columns": [ + "\"org_id\"", + "\"project_id\"" + ], + "where": null + }, + { + "kind": "foreign_key", + "table": "alert_escalation_runs", + "name": "alert_escalation_runs_incident_id_alert_incidents_id_fk", + "columns": [ + "incident_id" + ], + "foreignTable": "alert_incidents", + "foreignColumns": [ + "id" + ], + "onDelete": "CASCADE", + "onUpdate": "NO ACTION" + }, + { + "kind": "foreign_key", + "table": "alert_incident_events", + "name": "alert_incident_events_incident_id_alert_incidents_id_fk", + "columns": [ + "incident_id" + ], + "foreignTable": "alert_incidents", + "foreignColumns": [ + "id" + ], + "onDelete": "CASCADE", + "onUpdate": "NO ACTION" + }, + { + "kind": "foreign_key", + "table": "alert_linear_issues", + "name": "alert_linear_issues_destination_id_alert_destinations_id_fk", + "columns": [ + "destination_id" + ], + "foreignTable": "alert_destinations", + "foreignColumns": [ + "id" + ], + "onDelete": "CASCADE", + "onUpdate": "NO ACTION" + }, + { + "kind": "foreign_key", + "table": "alert_member_notifications", + "name": "alert_member_notifications_incident_id_alert_incidents_id_fk", + "columns": [ + "incident_id" + ], + "foreignTable": "alert_incidents", + "foreignColumns": [ + "id" + ], + "onDelete": "CASCADE", + "onUpdate": "NO ACTION" + }, + { + "kind": "foreign_key", + "table": "aws_connections", + "name": "aws_connections_source_id_sources_id_fk", + "columns": [ + "source_id" + ], + "foreignTable": "sources", + "foreignColumns": [ + "id" + ], + "onDelete": "CASCADE", + "onUpdate": "NO ACTION" + }, + { + "kind": "foreign_key", + "table": "cloud_security_findings", + "name": "cloud_security_findings_ujhY2Pd3JWVy_fk", + "columns": [ + "org_id", + "connection_id" + ], + "foreignTable": "aws_connections", + "foreignColumns": [ + "org_id", + "id" + ], + "onDelete": "CASCADE", + "onUpdate": "NO ACTION" + }, + { + "kind": "foreign_key", + "table": "cloud_security_service_states", + "name": "cloud_security_service_states_jHft8OtcW6A2_fk", + "columns": [ + "org_id", + "connection_id" + ], + "foreignTable": "aws_connections", + "foreignColumns": [ + "org_id", + "id" + ], + "onDelete": "CASCADE", + "onUpdate": "NO ACTION" + }, + { + "kind": "foreign_key", + "table": "cloudflare_logpush_connectors", + "name": "cloudflare_logpush_connectors_source_id_sources_id_fk", + "columns": [ + "source_id" + ], + "foreignTable": "sources", + "foreignColumns": [ + "id" + ], + "onDelete": "SET NULL", + "onUpdate": "NO ACTION" + }, + { + "kind": "foreign_key", + "table": "dashboard_shares", + "name": "dashboard_shares_dashboard_fk", + "columns": [ + "org_id", + "dashboard_id" + ], + "foreignTable": "dashboards", + "foreignColumns": [ + "org_id", + "id" + ], + "onDelete": "CASCADE", + "onUpdate": "NO ACTION" + }, + { + "kind": "foreign_key", + "table": "external_data_source_catalog_entries", + "name": "external_data_source_catalog_entries_x60VonL2VphD_fk", + "columns": [ + "source_id" + ], + "foreignTable": "external_data_sources", + "foreignColumns": [ + "id" + ], + "onDelete": "CASCADE", + "onUpdate": "NO ACTION" + }, + { + "kind": "foreign_key", + "table": "gcp_connectors", + "name": "gcp_connectors_source_id_sources_id_fk", + "columns": [ + "source_id" + ], + "foreignTable": "sources", + "foreignColumns": [ + "id" + ], + "onDelete": "CASCADE", + "onUpdate": "NO ACTION" + }, + { + "kind": "foreign_key", + "table": "gcp_cost_exports", + "name": "gcp_cost_exports_connector_id_gcp_connectors_id_fk", + "columns": [ + "connector_id" + ], + "foreignTable": "gcp_connectors", + "foreignColumns": [ + "id" + ], + "onDelete": "CASCADE", + "onUpdate": "NO ACTION" + }, + { + "kind": "foreign_key", + "table": "gcp_resources", + "name": "gcp_resources_connector_id_gcp_connectors_id_fk", + "columns": [ + "connector_id" + ], + "foreignTable": "gcp_connectors", + "foreignColumns": [ + "id" + ], + "onDelete": "CASCADE", + "onUpdate": "NO ACTION" + }, + { + "kind": "foreign_key", + "table": "oauth_connections", + "name": "oauth_connections_source_id_sources_id_fk", + "columns": [ + "source_id" + ], + "foreignTable": "sources", + "foreignColumns": [ + "id" + ], + "onDelete": "CASCADE", + "onUpdate": "NO ACTION" + }, + { + "kind": "foreign_key", + "table": "oncall_overrides", + "name": "oncall_overrides_schedule_id_oncall_schedules_id_fk", + "columns": [ + "schedule_id" + ], + "foreignTable": "oncall_schedules", + "foreignColumns": [ + "id" + ], + "onDelete": "CASCADE", + "onUpdate": "NO ACTION" + }, + { + "kind": "foreign_key", + "table": "planetscale_connections", + "name": "planetscale_connections_source_id_sources_id_fk", + "columns": [ + "source_id" + ], + "foreignTable": "sources", + "foreignColumns": [ + "id" + ], + "onDelete": "CASCADE", + "onUpdate": "NO ACTION" + }, + { + "kind": "foreign_key", + "table": "railway_connections", + "name": "railway_connections_source_id_sources_id_fk", + "columns": [ + "source_id" + ], + "foreignTable": "sources", + "foreignColumns": [ + "id" + ], + "onDelete": "CASCADE", + "onUpdate": "NO ACTION" + }, + { + "kind": "foreign_key", + "table": "scrape_target_checks", + "name": "scrape_target_checks_target_id_scrape_targets_id_fk", + "columns": [ + "target_id" + ], + "foreignTable": "scrape_targets", + "foreignColumns": [ + "id" + ], + "onDelete": "CASCADE", + "onUpdate": "NO ACTION" + }, + { + "kind": "foreign_key", + "table": "scrape_targets", + "name": "scrape_targets_source_id_sources_id_fk", + "columns": [ + "source_id" + ], + "foreignTable": "sources", + "foreignColumns": [ + "id" + ], + "onDelete": "CASCADE", + "onUpdate": "NO ACTION" + }, + { + "kind": "foreign_key", + "table": "search_console_sites", + "name": "search_console_sites_jBAHYyW36dnu_fk", + "columns": [ + "oauth_connection_id" + ], + "foreignTable": "oauth_connections", + "foreignColumns": [ + "id" + ], + "onDelete": "CASCADE", + "onUpdate": "NO ACTION" + }, + { + "kind": "foreign_key", + "table": "status_page_components", + "name": "status_page_components_monitor_id_uptime_monitors_id_fk", + "columns": [ + "monitor_id" + ], + "foreignTable": "uptime_monitors", + "foreignColumns": [ + "id" + ], + "onDelete": "SET NULL", + "onUpdate": "NO ACTION" + }, + { + "kind": "foreign_key", + "table": "status_page_components", + "name": "status_page_components_page_id_status_pages_id_fk", + "columns": [ + "page_id" + ], + "foreignTable": "status_pages", + "foreignColumns": [ + "id" + ], + "onDelete": "CASCADE", + "onUpdate": "NO ACTION" + }, + { + "kind": "foreign_key", + "table": "status_page_custom_domains", + "name": "status_page_custom_domains_page_id_status_pages_id_fk", + "columns": [ + "page_id" + ], + "foreignTable": "status_pages", + "foreignColumns": [ + "id" + ], + "onDelete": "CASCADE", + "onUpdate": "NO ACTION" + }, + { + "kind": "foreign_key", + "table": "status_page_incident_components", + "name": "status_page_incident_components_Bnqlt6wwKJty_fk", + "columns": [ + "component_id" + ], + "foreignTable": "status_page_components", + "foreignColumns": [ + "id" + ], + "onDelete": "CASCADE", + "onUpdate": "NO ACTION" + }, + { + "kind": "foreign_key", + "table": "status_page_incident_components", + "name": "status_page_incident_components_tBn6mEz4FenY_fk", + "columns": [ + "incident_id" + ], + "foreignTable": "status_page_incidents", + "foreignColumns": [ + "id" + ], + "onDelete": "CASCADE", + "onUpdate": "NO ACTION" + }, + { + "kind": "foreign_key", + "table": "status_page_incident_updates", + "name": "status_page_incident_updates_3LDDUAhznHPM_fk", + "columns": [ + "incident_id" + ], + "foreignTable": "status_page_incidents", + "foreignColumns": [ + "id" + ], + "onDelete": "CASCADE", + "onUpdate": "NO ACTION" + }, + { + "kind": "foreign_key", + "table": "status_page_incidents", + "name": "status_page_incidents_page_id_status_pages_id_fk", + "columns": [ + "page_id" + ], + "foreignTable": "status_pages", + "foreignColumns": [ + "id" + ], + "onDelete": "CASCADE", + "onUpdate": "NO ACTION" + }, + { + "kind": "foreign_key", + "table": "supabase_connections", + "name": "supabase_connections_source_id_sources_id_fk", + "columns": [ + "source_id" + ], + "foreignTable": "sources", + "foreignColumns": [ + "id" + ], + "onDelete": "CASCADE", + "onUpdate": "NO ACTION" + }, + { + "kind": "foreign_key", + "table": "supabase_project_insights", + "name": "supabase_project_insights_project_id_supabase_projects_id_fk", + "columns": [ + "project_id" + ], + "foreignTable": "supabase_projects", + "foreignColumns": [ + "id" + ], + "onDelete": "CASCADE", + "onUpdate": "NO ACTION" + }, + { + "kind": "foreign_key", + "table": "supabase_projects", + "name": "supabase_projects_connection_id_supabase_connections_id_fk", + "columns": [ + "connection_id" + ], + "foreignTable": "supabase_connections", + "foreignColumns": [ + "id" + ], + "onDelete": "CASCADE", + "onUpdate": "NO ACTION" + }, + { + "kind": "foreign_key", + "table": "supabase_projects", + "name": "supabase_projects_log_drain_source_id_sources_id_fk", + "columns": [ + "log_drain_source_id" + ], + "foreignTable": "sources", + "foreignColumns": [ + "id" + ], + "onDelete": "SET NULL", + "onUpdate": "NO ACTION" + }, + { + "kind": "foreign_key", + "table": "uptime_monitor_daily", + "name": "uptime_monitor_daily_monitor_id_uptime_monitors_id_fk", + "columns": [ + "monitor_id" + ], + "foreignTable": "uptime_monitors", + "foreignColumns": [ + "id" + ], + "onDelete": "CASCADE", + "onUpdate": "NO ACTION" + }, + { + "kind": "foreign_key", + "table": "uptime_monitor_states", + "name": "uptime_monitor_states_monitor_id_uptime_monitors_id_fk", + "columns": [ + "monitor_id" + ], + "foreignTable": "uptime_monitors", + "foreignColumns": [ + "id" + ], + "onDelete": "CASCADE", + "onUpdate": "NO ACTION" + }, + { + "kind": "foreign_key", + "table": "vcs_installations", + "name": "vcs_installations_source_id_sources_id_fk", + "columns": [ + "source_id" + ], + "foreignTable": "sources", + "foreignColumns": [ + "id" + ], + "onDelete": "CASCADE", + "onUpdate": "NO ACTION" + }, + { + "kind": "foreign_key", + "table": "vercel_connections", + "name": "vercel_connections_source_id_sources_id_fk", + "columns": [ + "source_id" + ], + "foreignTable": "sources", + "foreignColumns": [ + "id" + ], + "onDelete": "CASCADE", + "onUpdate": "NO ACTION" + } + ] +} diff --git a/packages/db/src/tables/index.ts b/packages/db/src/tables/index.ts index 2305d4301e..922a8626c4 100644 --- a/packages/db/src/tables/index.ts +++ b/packages/db/src/tables/index.ts @@ -92,6 +92,7 @@ import { SavedViews } from "./saved-views" import { ScrapeTargets, ScrapeTargetChecks } from "./scrape-targets" import { SearchConsoleSites } from "./search-console-sites" import { ServiceMapWorldEntities } from "./service-map-world" +import { SourceMapFiles } from "./source-maps" import { SecurityAuditEvents, SecurityAuditFindings, @@ -194,6 +195,7 @@ export * from "./scrape-targets" export * from "./search-console-sites" export * from "./security-audit" export * from "./service-map-world" +export * from "./source-maps" export * from "./sources" export * from "./status-pages" export * from "./supabase" @@ -313,6 +315,7 @@ export const allTables: ReadonlyArray> = [ ServiceMapWorldEntities, ScrapeTargetChecks, SearchConsoleSites, + SourceMapFiles, SecurityAuditTargets, SecurityAuditRuns, SecurityAuditUnits, diff --git a/packages/db/src/tables/source-maps.ts b/packages/db/src/tables/source-maps.ts new file mode 100644 index 0000000000..4bb11e6274 --- /dev/null +++ b/packages/db/src/tables/source-maps.ts @@ -0,0 +1,40 @@ +import * as PG from "@maple-dev/effect-orm/postgres" +import { OrgId, SourceMapFileId } from "@maple/primitives" + +const sourceMapFilesColumns = { + id: PG.brand(PG.text, SourceMapFileId), + orgId: PG.column(PG.brand(PG.text, OrgId), { name: "org_id" }), + debugId: PG.column(PG.nullable(PG.text), { name: "debug_id" }), + serviceName: PG.column(PG.nullable(PG.text), { name: "service_name" }), + version: PG.nullable(PG.text), + minifiedPath: PG.column(PG.text, { name: "minified_path" }), + sizeBytes: PG.column(PG.int4, { name: "size_bytes" }), + hasSourcesContent: PG.column(PG.bool, { name: "has_sources_content" }), + objectKey: PG.column(PG.text, { name: "object_key" }), + createdAt: PG.column(PG.timestamptzMillis, { name: "created_at", defaultExpr: "now()" }), + lastUsedAt: PG.column(PG.nullable(PG.timestamptzMillis), { name: "last_used_at" }), +} + +type SourceMapFilesColumns = PG.ColumnsOf + +/** + * Uploaded JavaScript source maps. The bytes live in R2 under `objectKey`; a row is found by debug + * id first, else by service + version + minified path. Deleted 90 days after its last use. + */ +export const SourceMapFiles = PG.table("source_map_files", { + columns: sourceMapFilesColumns, + primaryKey: ["id"], + indexes: [ + PG.uniqueIndex("source_map_files_org_debug_id_idx", ["orgId", "debugId"]), + // Only maps without a debug id own a release path: builds with their own ids may share one. + PG.uniqueIndex( + "source_map_files_org_release_path_idx", + ["orgId", "serviceName", "version", "minifiedPath"], + { where: ($) => $.debugId.isNull() }, + ), + PG.index("source_map_files_org_created_idx", ["orgId", "createdAt"]), + ], + tenantColumn: "orgId", +}) + +export type SourceMapFileRow = PG.SelectRowOf diff --git a/packages/domain/package.json b/packages/domain/package.json index cc000ebb64..f166ff86f4 100644 --- a/packages/domain/package.json +++ b/packages/domain/package.json @@ -47,6 +47,7 @@ "./dashboard-shares": "./src/dashboard-shares.ts", "./electric-shapes": "./src/electric-shapes.ts", "./error-issues": "./src/error-issues.ts", + "./errors/js-stack": "./src/errors/js-stack.ts", "./escalation-chains": "./src/escalation-chains.ts", "./fix-verification": "./src/fix-verification.ts", "./investigations": "./src/investigations.ts", @@ -129,6 +130,7 @@ "@maple/primitives": "workspace:*", "@maple/query-model": "workspace:*", "@maple/security-audit": "workspace:*", + "@maple/sourcemaps": "workspace:*", "@maple/strings": "workspace:*", "@maple/widgets": "workspace:*", "effect": "catalog:effect", diff --git a/packages/domain/src/audit-actions.ts b/packages/domain/src/audit-actions.ts index 50057b83ca..72b17ece5a 100644 --- a/packages/domain/src/audit-actions.ts +++ b/packages/domain/src/audit-actions.ts @@ -42,6 +42,8 @@ export const AuditResources = { verbs: ["created", "updated", "deleted"], }, ingest_rule: { prefix: PublicIdPrefixes.ingestRule, verbs: ["created", "updated", "deleted"] }, + /** An uploaded JavaScript source map; its path and release are in `metadata`. */ + source_map: { prefix: PublicIdPrefixes.sourceMap, verbs: ["uploaded", "deleted"] }, /** External data sources; `metadata` says whether a secret changed, never its value. */ data_source: { prefix: PublicIdPrefixes.dataSource, @@ -288,6 +290,7 @@ export const AuditResourceLabels = { api_key: "API key", attribute_mapping: "Attribute mapping", ingest_rule: "Ingest rule", + source_map: "Source map", data_source: "Data source", dashboard: "Dashboard", chat_integration: "Chat integration", @@ -384,6 +387,8 @@ export const AuditActionLabels = { "attribute_mapping.updated": "Updated attribute mapping", "attribute_mapping.deleted": "Deleted attribute mapping", "ingest_rule.created": "Created ingest rule", + "source_map.uploaded": "Uploaded source map", + "source_map.deleted": "Deleted source map", "ingest_rule.updated": "Updated ingest rule", "ingest_rule.deleted": "Deleted ingest rule", "data_source.created": "Connected data source", diff --git a/packages/domain/src/errors/js-stack.test.ts b/packages/domain/src/errors/js-stack.test.ts new file mode 100644 index 0000000000..ad431f3c08 --- /dev/null +++ b/packages/domain/src/errors/js-stack.test.ts @@ -0,0 +1,197 @@ +import { Array as Arr, Schema, String as Str } from "effect" +import { describe, expect, it } from "vitest" +import { + SymbolicatedStack, + decodeDebugIds, + isInAppPath, + parseJsStack, + urlMatchesMinifiedPath, +} from "./js-stack" + +const V8 = `TypeError: Cannot read properties of undefined (reading 'id') + at handleClick (https://app.example.com/assets/index-Bx81.js:1:2345) + at https://app.example.com/assets/vendor.js?v=3:12:40 + at async loadUser (https://app.example.com/assets/index-Bx81.js:2:10) + at new Store (webpack-internal:///./src/store.ts:7:3) + at eval (eval at compile (https://app.example.com/assets/index-Bx81.js:3:15), :1:1) + at Array.map () + at fiber (#12) + at myEffectSpan` + +describe("parseJsStack", () => { + it("parses V8 frames top first and keeps the header out of the frames", () => { + const parsed = parseJsStack(V8) + expect(parsed.message).toBe("TypeError: Cannot read properties of undefined (reading 'id')") + expect( + Arr.map(parsed.frames, (frame) => [frame.function, frame.url, frame.line, frame.column]), + ).toEqual([ + ["handleClick", "https://app.example.com/assets/index-Bx81.js", 1, 2345], + [null, "https://app.example.com/assets/vendor.js?v=3", 12, 40], + ["loadUser", "https://app.example.com/assets/index-Bx81.js", 2, 10], + ["Store", "webpack-internal:///./src/store.ts", 7, 3], + ["eval", "https://app.example.com/assets/index-Bx81.js", 3, 15], + ["Array.map", null, null, null], + ]) + expect(parsed.frames[0]?.raw).toBe( + "at handleClick (https://app.example.com/assets/index-Bx81.js:1:2345)", + ) + }) + + it("parses Firefox and Safari frames", () => { + const parsed = parseJsStack( + Arr.join( + [ + "render@https://app.example.com/assets/index.js:10:5", + "@https://app.example.com/assets/index.js:1:1", + "global code@https://app.example.com/assets/main.js:3:9", + "[native code]", + "lazy@https://cdn.example.com/node_modules/@scope/pkg/index.js:4:2", + ], + "\n", + ), + ) + expect(parsed.message).toBeNull() + expect( + Arr.map(parsed.frames, (frame) => [frame.function, frame.url, frame.line, frame.column]), + ).toEqual([ + ["render", "https://app.example.com/assets/index.js", 10, 5], + [null, "https://app.example.com/assets/index.js", 1, 1], + ["global code", "https://app.example.com/assets/main.js", 3, 9], + ["lazy", "https://cdn.example.com/node_modules/@scope/pkg/index.js", 4, 2], + ]) + }) + + it("keeps a Promise combinator frame, with no location, between two app frames", () => { + const { frames } = parseJsStack( + "Error: boom\n at child (https://a.test/app.js:1:5)\n at async Promise.all (index 0)\n at async parent (https://a.test/app.js:1:40)", + ) + expect(Arr.map(frames, (frame) => [frame.function, frame.url])).toEqual([ + ["child", "https://a.test/app.js"], + ["Promise.all", null], + ["parent", "https://a.test/app.js"], + ]) + }) + + it("parses hostile lines in linear time", () => { + // Each line is its prefix plus a repeated unit, filled to `length` characters. + const attackLines = (length: number) => + Arr.map( + [ + ["at ", " "], + ["at (", " (a"], + ["@a", " "], + ["at a (", ":1"], + ["x@", " line 1"], + ["at eval (eval at ", "(("], + ] as const, + ([prefix, unit]) => + `${prefix}${Str.repeat(Math.floor((length - prefix.length) / unit.length))(unit)}`, + ) + // 100k-char lines are past the frame cap; ones just under it go through the whole parser. + Arr.forEach(attackLines(1_999), (line) => expect(line.length).toBeLessThanOrEqual(2_000)) + Arr.forEach([100_000, 1_999], (length) => + Arr.forEach(attackLines(length), (line) => { + const started = performance.now() + parseJsStack(`Error: x\n${line}\n${line}`) + expect(performance.now() - started).toBeLessThan(50) + }), + ) + }) + + it("reads the concrete location of a nested eval origin", () => { + const { frames } = parseJsStack( + "Error\n at eval (eval at a (eval at b (https://cdn.test/app.js:10:3)), :1:1)", + ) + expect(Arr.map(frames, (frame) => [frame.function, frame.url, frame.line, frame.column])).toEqual([ + ["eval", "https://cdn.test/app.js", 10, 3], + ]) + }) + + it("keeps a header with an `@` in its message as the message, not a frame", () => { + const parsed = parseJsStack( + "Error: invalid token for user@api:401\n at a (https://a.test/app.js:1:5)\nrender@https://a.test/app.js:2:3", + ) + expect(parsed.message).toBe("Error: invalid token for user@api:401") + expect(Arr.map(parsed.frames, (frame) => [frame.function, frame.url])).toEqual([ + ["a", "https://a.test/app.js"], + ["render", "https://a.test/app.js"], + ]) + }) + + it("skips caused by lines and returns no frames for a non-JS stack", () => { + expect(parseJsStack("Error: boom\ncaused by: Error: inner").frames).toEqual([]) + expect(parseJsStack('Traceback (most recent call last):\n File "a.py", line 1').frames).toEqual([]) + expect(parseJsStack("").message).toBeNull() + }) +}) + +describe("decodeDebugIds", () => { + it("reads the JSON object and treats anything else as empty", () => { + const ids = decodeDebugIds('{"https://a.example/x.js":"0f1e2d3c-0000-4000-8000-000000000001"}') + expect(ids.get("https://a.example/x.js")).toBe("0f1e2d3c-0000-4000-8000-000000000001") + expect(decodeDebugIds(undefined).size).toBe(0) + expect(decodeDebugIds("{not json").size).toBe(0) + expect(decodeDebugIds('["a"]').size).toBe(0) + expect(decodeDebugIds('{"a":1}').size).toBe(0) + }) +}) + +describe("urlMatchesMinifiedPath", () => { + it.each([ + ["https://app.example.com/assets/index-Bx81.js", "assets/index-Bx81.js", true], + ["https://app.example.com/assets/index-Bx81.js?v=2#x", "assets/index-Bx81.js", true], + ["https://app.example.com/base/assets/index-Bx81.js", "assets/index-Bx81.js", true], + ["https://app.example.com/assets/index-Bx81.js", "/assets/index-Bx81.js", true], + ["https://app.example.com/myassets/index-Bx81.js", "assets/index-Bx81.js", false], + ["https://app.example.com/assets/index-Bx81.js", "assets/other.js", false], + ["file:///srv/app/dist/main.js", "dist/main.js", true], + ["app:///dist/main.js", "dist/main.js", true], + ["/srv/app/dist/main.js", "dist/main.js", true], + ["https://app.example.com/assets/index.js", "", false], + ])("%s against %s is %s", (url, path, expected) => { + expect(urlMatchesMinifiedPath(url, path)).toBe(expected) + }) +}) + +describe("isInAppPath", () => { + it.each([ + ["src/components/Button.tsx", true], + ["https://app.example.com/assets/index.js", true], + ["../node_modules/react-dom/cjs/react-dom.development.js", false], + ["webpack/runtime/jsonp chunk loading", false], + ["webpack/bootstrap", false], + ["chrome-extension://abc/content.js", false], + ["moz-extension://abc/content.js", false], + ["safari-extension://abc/content.js", false], + ["node:internal/process/task_queues", false], + ["", false], + ["native", false], + ])("%s is %s", (path, expected) => { + expect(isInAppPath(path)).toBe(expected) + }) +}) + +describe("SymbolicatedStack schema", () => { + it("round-trips the wire shape", () => { + const wire = { + status: "partial", + frames: [ + { + raw: "at a (https://x/a.js:1:1)", + function: "a", + file: "src/a.ts", + line: 3, + column: 1, + in_app: true, + resolved: true, + context: { pre: ["x"], line: "y", post: [] }, + }, + ], + missing: ["https://x/b.js"], + } + expect( + Schema.encodeSync(SymbolicatedStack)(Schema.decodeUnknownSync(SymbolicatedStack)(wire)), + ).toEqual(wire) + expect(() => Schema.decodeUnknownSync(SymbolicatedStack)({ ...wire, status: "done" })).toThrow() + }) +}) diff --git a/packages/domain/src/errors/js-stack.ts b/packages/domain/src/errors/js-stack.ts new file mode 100644 index 0000000000..d94bbf6625 --- /dev/null +++ b/packages/domain/src/errors/js-stack.ts @@ -0,0 +1,260 @@ +import { Array as Arr, Option, Record as Rec, Schema, String as Str } from "effect" + +/** Span event attribute carrying `{ "": "" }` as a JSON string. */ +export const DEBUG_IDS_ATTRIBUTE = "maple.exception.debug_ids" + +/** One stack frame as written in the stack trace, before any source map. */ +export interface ParsedFrame { + readonly raw: string + readonly function: string | null + readonly url: string | null + readonly line: number | null + readonly column: number | null +} + +export interface ParsedJsStack { + /** The `TypeError: msg` header line, when the stack starts with one. */ + readonly message: string | null + /** Top of stack first. */ + readonly frames: ReadonlyArray +} + +export const StackFrameContext = Schema.Struct({ + pre: Schema.Array(Schema.String), + line: Schema.String, + post: Schema.Array(Schema.String), +}) +export type StackFrameContext = typeof StackFrameContext.Type + +export const StackFrame = Schema.Struct({ + raw: Schema.String, + function: Schema.NullOr(Schema.String), + /** True when a source map supplied `function`; otherwise it is the name as the stack wrote it. */ + function_from_map: Schema.optionalKey(Schema.Boolean), + file: Schema.NullOr(Schema.String), + line: Schema.NullOr(Schema.Number), + column: Schema.NullOr(Schema.Number), + in_app: Schema.Boolean, + resolved: Schema.Boolean, + context: Schema.NullOr(StackFrameContext), +}) +export type StackFrame = typeof StackFrame.Type + +export const SymbolicationStatus = Schema.Literals(["resolved", "partial", "missing_map", "not_applicable"]) +export type SymbolicationStatus = typeof SymbolicationStatus.Type + +export const SymbolicatedStack = Schema.Struct({ + status: SymbolicationStatus, + frames: Schema.Array(StackFrame), + missing: Schema.Array(Schema.String), +}) +export type SymbolicatedStack = typeof SymbolicatedStack.Type + +/** + * Stack text is customer data, so lines are parsed with index splits and tail checks, never one + * backtracking pattern, and overlong lines are not frames at all. + */ +const MAX_FRAME_LINE = 2000 +const DIGITS = /^\d+$/u +const GECKO_EVAL_TAIL = /^ line (\d+) > (?:eval|Function)(?::\d+:\d+)?$/u +const PROMISE_INDEX = /^index \d+$/u +const NO_LOCATION = new Set(["native", "", "[native code]", "unknown location"]) + +interface Location { + readonly url: string | null + readonly line: number | null + readonly column: number | null +} + +const NOWHERE: Location = { url: null, line: null, column: null } + +/** The text before and after the first (or last) `separator`, when it occurs. */ +const splitAt = (text: string, separator: string, last = false) => + Option.map((last ? Str.lastIndexOf(separator) : Str.indexOf(separator))(text), (index) => ({ + before: Str.slice(0, index)(text), + after: Str.slice(index + separator.length)(text), + })) + +/** `url:line:column` or `url:line`, split at the last colons; the url must not be empty. */ +const parseUrlLocation = (location: string): Option.Option => + Option.flatMap( + Option.filter( + splitAt(location, ":", true), + ({ before, after }) => before !== "" && DIGITS.test(after), + ), + ({ before, after }) => + Option.match( + Option.filter( + splitAt(before, ":", true), + (inner) => inner.before !== "" && DIGITS.test(inner.after), + ), + { + onNone: (): Option.Option => + Option.some({ url: before, line: Number(after), column: null }), + onSome: (inner): Option.Option => + Option.some({ url: inner.before, line: Number(inner.after), column: Number(after) }), + }, + ), + ) + +/** `eval at fn (url:1:2), :3:4`: the eval call site, else no location. */ +const parseEvalOrigin = (location: string): Location => { + // The innermost origin: nested evals read `eval at a (eval at b (url:1:2)), ...`, so the text + // between the first `)` and the last `(` before it is the concrete call site. + const origin = Option.flatMap(splitAt(location, ")"), ({ before }) => + Option.map(splitAt(before, "(", true), ({ after }) => after), + ) + const located = Option.flatMap( + Option.filter(origin, (text) => !/\s/u.test(text)), + parseUrlLocation, + ) + return Option.isSome(located) && located.value.column !== null ? located.value : NOWHERE +} + +const parseLocation = (location: string): Option.Option => { + const trimmed = Str.trim(location) + if (NO_LOCATION.has(trimmed)) return Option.some(NOWHERE) + // `at async Promise.all (index 0)`: a combinator between two app frames, kept so the frame + // below it is not taken for the direct caller of the one above. + if (PROMISE_INDEX.test(trimmed)) return Option.some(NOWHERE) + if (Str.startsWith("eval at ")(trimmed)) return Option.some(parseEvalOrigin(trimmed)) + // Firefox eval frames: `url line 3 > eval:1:1`. + const geckoEval = Option.flatMap( + Option.filter(splitAt(trimmed, " line "), ({ before }) => before !== ""), + ({ before, after }) => + Option.map(Option.fromNullishOr(GECKO_EVAL_TAIL.exec(` line ${after}`)?.[1]), (line) => ({ + url: before, + line: Number(line), + column: null, + })), + ) + return Option.isSome(geckoEval) ? geckoEval : parseUrlLocation(trimmed) +} + +const nonEmpty = (value: string | undefined): string | null => { + const trimmed = Str.trim(value ?? "") + return trimmed === "" ? null : trimmed +} + +const frameOf = (raw: string, fn: string | null, location: Location): ParsedFrame => ({ + raw: Str.trim(raw), + function: fn, + url: location.url, + line: location.line, + column: location.column, +}) + +/** `rest` without a leading `word ` and the whitespace after it. */ +const dropWord = (rest: string, word: string): string => + Str.startsWith(`${word} `)(rest) || Str.startsWith(`${word}\t`)(rest) + ? Str.trimStart(Str.slice(word.length)(rest)) + : rest + +/** A V8 frame after its `at `: `fn (location)`, or a bare location. */ +const parseV8Frame = (raw: string, rest: string): Option.Option => { + const body = dropWord(dropWord(rest, "async"), "new") + // The function ends at the first ` (`; the location runs to the final `)`. + const call = Option.filter(splitAt(body, " ("), () => Str.endsWith(")")(body)) + if (Option.isSome(call)) { + return Option.map(parseLocation(Str.slice(0, -1)(call.value.after)), (location) => + frameOf(raw, nonEmpty(call.value.before), location), + ) + } + // `at spanName` alone is an Effect span, not a code location. + return Option.flatMap(parseLocation(body), (loc) => + loc.url === null && !NO_LOCATION.has(Str.trim(body)) + ? Option.none() + : Option.some(frameOf(raw, null, loc)), + ) +} + +/** A frame from one stack line; none for headers, `caused by` lines and Effect span lines with no location. */ +export const parseJsFrame = (raw: string): Option.Option => { + if (raw.length > MAX_FRAME_LINE) return Option.none() + const line = Str.trim(raw) + if (Str.startsWith("at ")(line) || Str.startsWith("at\t")(line)) { + const rest = Str.trim(Str.slice(3)(line)) + return rest === "" ? Option.none() : parseV8Frame(raw, rest) + } + // Firefox and Safari: `fn@location`, the function never holding an `@`. A `: ` before the `@` + // is a message header (`Error: bad token for user@api:401`), never a function name. + return Option.flatMap( + Option.filter( + splitAt(line, "@"), + ({ before, after }) => Str.trim(after) !== "" && !Str.includes(": ")(before), + ), + ({ before, after }) => Option.map(parseLocation(after), (loc) => frameOf(raw, nonEmpty(before), loc)), + ) +} + +/** Parses V8, Firefox and Safari stack traces, top of stack first. */ +export const parseJsStack = (stacktrace: string): ParsedJsStack => { + const lines = Arr.filter(Str.split(stacktrace, /\r?\n/u), (line) => Str.trim(line) !== "") + const frames = Arr.getSomes(Arr.map(lines, parseJsFrame)) + const first = Arr.head(lines) + const message = Option.match(first, { + onNone: () => null, + onSome: (line) => (Option.isSome(parseJsFrame(line)) ? null : Str.trim(line)), + }) + return { message, frames } +} + +const DebugIdsJson = Schema.fromJsonString(Schema.Record(Schema.String, Schema.String)) +const decodeDebugIdsJson = Schema.decodeUnknownOption(DebugIdsJson) + +/** Decodes the `maple.exception.debug_ids` attribute; anything malformed is an empty map. */ +export const decodeDebugIds = (attr: string | undefined): ReadonlyMap => + attr === undefined + ? new Map() + : Option.match(decodeDebugIdsJson(attr), { + onNone: () => new Map(), + onSome: (record) => new Map(Rec.toEntries(record)), + }) + +const SCHEME_AND_AUTHORITY = /^[A-Za-z][A-Za-z0-9+.-]*:\/\/[^/]*/u +const decodeUriPart = Option.liftThrowable(decodeURIComponent) + +const stripLeadingSlashes = Str.replace(/^(?:\.\/|\/)+/u, "") + +/** + * The path part of a frame URL or file path, percent-decoded (raw when it does not decode): + * no scheme, host, query, hash or leading `/` and `./`. + */ +export const frameUrlPath = (url: string): string => { + const noQuery = Str.replace(/[?#].*$/u, "")(Str.trim(url)) + const path = Str.replace(SCHEME_AND_AUTHORITY, "")(noQuery) + return stripLeadingSlashes(Option.getOrElse(decodeUriPart(path), () => path)) +} + +/** True when the frame URL's path is the stored minified path or ends with it at a `/` boundary. */ +export const urlMatchesMinifiedPath = (url: string, minifiedPath: string): boolean => { + // The stored path is already normalized at upload; a `#` or `?` in it is part of the file name. + const target = stripLeadingSlashes(Str.trim(minifiedPath)) + if (target === "") return false + const path = frameUrlPath(url) + return path === target || Str.endsWith(`/${target}`)(path) +} + +/** A frame URL a source map can belong to: a JavaScript file or a served URL. */ +export const isSourceMappableUrl = (url: string): boolean => { + const path = Str.toLowerCase(Str.replace(/[?#].*$/u, "")(url)) + return /\.(?:m|c)?js$/u.test(path) || /^https?:\/\//u.test(path) +} + +const NOT_IN_APP_FRAGMENTS = [ + "node_modules/", + "webpack/runtime", + "webpack/bootstrap", + "chrome-extension://", + "moz-extension://", + "safari-extension://", + "", +] + +/** False for dependency, bundler runtime, browser extension and engine-internal frames. */ +export const isInAppPath = (path: string): boolean => { + const normalized = Str.replace(/\\/gu, "/")(Str.trim(path)) + if (normalized === "native" || normalized === "[native code]") return false + if (Str.startsWith("node:")(normalized)) return false + return !Arr.some(NOT_IN_APP_FRAGMENTS, (fragment) => Str.includes(fragment)(normalized)) +} diff --git a/packages/domain/src/generated/anticipated-error-identifiers.ts b/packages/domain/src/generated/anticipated-error-identifiers.ts index 124872066f..9c4e6f074d 100644 --- a/packages/domain/src/generated/anticipated-error-identifiers.ts +++ b/packages/domain/src/generated/anticipated-error-identifiers.ts @@ -217,6 +217,9 @@ export const ANTICIPATED_ERROR_IDENTIFIER_LIST: ReadonlyArray = [ "@maple/http/security-audit/SecurityAuditTargetNotFoundError", "@maple/http/service-map-world/WorldConflictError", "@maple/http/service-map-world/WorldInvalidOpsError", + "@maple/http/sourcemaps/SourceMapInvalidError", + "@maple/http/sourcemaps/SourceMapNotFoundError", + "@maple/http/sourcemaps/SourceMapTooLargeError", "@maple/http/v1/V1RequestValidationError", "@maple/http/v2/CursorInvalidError", "@maple/http/v2/CursorSortMismatchError", diff --git a/packages/domain/src/http/errors.ts b/packages/domain/src/http/errors.ts index 90a97258cd..88f349dcff 100644 --- a/packages/domain/src/http/errors.ts +++ b/packages/domain/src/http/errors.ts @@ -44,6 +44,7 @@ import { WorkflowState, } from "../error-issues" import { AnalystAccess } from "./analyst-access" +import { SymbolicatedStack } from "../errors/js-stack" import { GroupingRule } from "../tinybird/grouping" import { GroupingConfig, OrgGroupingRule } from "../tinybird/grouping-rules" export { @@ -338,6 +339,8 @@ export class ErrorIssueDetailResponse extends Schema.Class( diff --git a/packages/domain/src/http/index.ts b/packages/domain/src/http/index.ts index 9c048029d5..3c0b16be26 100644 --- a/packages/domain/src/http/index.ts +++ b/packages/domain/src/http/index.ts @@ -75,6 +75,7 @@ export * from "./error-policy" export * from "./ingest-attribute-mappings" export * from "./ingest-rules" export * from "./ingest-keys" +export * from "./source-maps" export * from "./sources" export * from "./integrations" export * from "./oauth-return" diff --git a/packages/domain/src/http/source-maps.ts b/packages/domain/src/http/source-maps.ts new file mode 100644 index 0000000000..596d2ecba0 --- /dev/null +++ b/packages/domain/src/http/source-maps.ts @@ -0,0 +1,76 @@ +import { Schema } from "effect" +import { SourceMapFileId } from "@maple/primitives" +import { HttpTaggedError } from "./error-policy" + +export { SOURCE_MAP_MAX_BYTES } from "@maple/sourcemaps/limits" + +/** The upload is not a usable source map, or its parameters do not identify one. */ +export class SourceMapInvalidError extends HttpTaggedError()( + "@maple/http/sourcemaps/SourceMapInvalidError", + { + message: Schema.String, + param: Schema.optionalKey(Schema.String), + }, + { + status: 400, + code: "source_map_invalid", + title: "Invalid source map", + param: (error) => error.param, + retry: "never", + recovery: "fix_request", + exposure: "public_message", + }, +) {} + +export class SourceMapTooLargeError extends HttpTaggedError()( + "@maple/http/sourcemaps/SourceMapTooLargeError", + { + message: Schema.String, + sizeBytes: Schema.Number, + }, + { + status: 413, + code: "source_map_too_large", + title: "Source map is too large", + message: "Source maps are limited to 10 MiB each, the largest Maple can symbolicate with.", + retry: "never", + recovery: "fix_request", + exposure: "public_message", + }, +) {} + +export class SourceMapNotFoundError extends HttpTaggedError()( + "@maple/http/sourcemaps/SourceMapNotFoundError", + { + message: Schema.String, + sourceMapId: SourceMapFileId, + }, + { + status: 404, + code: "source_map_not_found", + title: "Source map not found", + message: "No such source map.", + param: "id", + retry: "never", + recovery: "none", + exposure: "redacted", + }, +) {} + +/** Postgres or the object store failed; `cause` stays server-side. */ +export class SourceMapStorageError extends HttpTaggedError()( + "@maple/http/sourcemaps/SourceMapStorageError", + { + message: Schema.String, + cause: Schema.optionalKey(Schema.String), + }, + { + status: 503, + code: "source_maps_unavailable", + title: "Source maps are temporarily unavailable", + message: "Source maps are temporarily unavailable. Retry in a few seconds.", + retry: "backoff", + recovery: "retry", + exposure: "redacted", + }, +) {} diff --git a/packages/domain/src/http/v2/api.ts b/packages/domain/src/http/v2/api.ts index ae799d164b..44ce0b53b5 100644 --- a/packages/domain/src/http/v2/api.ts +++ b/packages/domain/src/http/v2/api.ts @@ -10,6 +10,7 @@ import { V2AlertMaintenanceWindowsApiGroup } from "./alert-maintenance-windows" import { V2AlertRulesApiGroup } from "./alert-rules" import { V2ApiKeysApiGroup } from "./api-keys" import { V2AttributeMappingsApiGroup } from "./attribute-mappings" +import { V2SourceMapsApiGroup } from "./source-maps" import { V2AuditLogApiGroup } from "./audit-log" import { V2DashboardsApiGroup } from "./dashboards" import { V2DataSourcesApiGroup } from "./data-sources" @@ -124,6 +125,7 @@ export class MapleApiV2 extends HttpApi.make("MapleApiV2") .add(V2AwsIntegrationsApiGroup) .add(V2ErrorIssuesApiGroup) .add(V2AttributeMappingsApiGroup) + .add(V2SourceMapsApiGroup) .add(V2DataSourcesApiGroup) .add(V2IngestRulesApiGroup) .add(V2AuditLogApiGroup) diff --git a/packages/domain/src/http/v2/error-issues.ts b/packages/domain/src/http/v2/error-issues.ts index 6f31ca0058..89a868f309 100644 --- a/packages/domain/src/http/v2/error-issues.ts +++ b/packages/domain/src/http/v2/error-issues.ts @@ -14,6 +14,7 @@ import { } from "../errors" import { SpanId, TraceId, UserId } from "@maple/primitives" import { AuditedRead } from "../audit-log" +import { SymbolicatedStack } from "../../errors/js-stack" import { AuthorizationV2 } from "./auth" import { ListOf, ListQuery, Timestamp } from "./envelopes" import { defineV2Error, V2CursorInvalid, V2CursorSortMismatch, V2ParameterInvalid } from "./errors" @@ -136,6 +137,13 @@ export const V2ErrorIncident = Schema.Struct({ }).annotate({ identifier: "ErrorIncident", title: "Error incident" }) export type V2ErrorIncident = Schema.Schema.Type +export const V2SymbolicatedStack = SymbolicatedStack.annotate({ + identifier: "SymbolicatedStack", + title: "Symbolicated stack", + description: + "A JavaScript stack trace mapped through uploaded source maps, top of stack first. `status` is `resolved` when every frame with a file mapped, `partial` when some did, `missing_map` when none did (`missing` lists the files with no map) and `not_applicable` when the trace has no JavaScript frames.", +}) + export const V2ErrorIssueDetail = Schema.Struct({ ...V2ErrorIssue.fields, timeseries: Schema.Array(V2ErrorIssueTimeseriesPoint), @@ -144,6 +152,8 @@ export const V2ErrorIssueDetail = Schema.Struct({ environments: Schema.Array(V2ErrorIssueEnvironment), /** The newest stack trace in the window; null when no occurrence there carried one. */ latest_stacktrace: Schema.optionalKey(Schema.NullOr(Schema.String)), + /** `latest_stacktrace` mapped through the uploaded source maps; null when there is no stack. */ + latest_stack: Schema.optionalKey(Schema.NullOr(V2SymbolicatedStack)), }).annotate({ identifier: "ErrorIssueDetail", title: "Error issue detail", diff --git a/packages/domain/src/http/v2/index.ts b/packages/domain/src/http/v2/index.ts index dea5526ed1..513b9478bf 100644 --- a/packages/domain/src/http/v2/index.ts +++ b/packages/domain/src/http/v2/index.ts @@ -37,6 +37,7 @@ export * from "./resource-ids" export * from "./route-not-found" export * from "./scrape-targets" export * from "./session-replays" +export * from "./source-maps" export * from "./uptime-monitors" export * from "./slos" export * from "./users" diff --git a/packages/domain/src/http/v2/openapi.test.ts b/packages/domain/src/http/v2/openapi.test.ts index a30e32e566..efff58befc 100644 --- a/packages/domain/src/http/v2/openapi.test.ts +++ b/packages/domain/src/http/v2/openapi.test.ts @@ -105,6 +105,7 @@ describe("MapleApiV2 OpenAPI", () => { "DELETE /v2/mobile_devices/{token}/live_activities/{incident_id}", "DELETE /v2/scrape_targets/{id}", "DELETE /v2/slos/{id}", + "DELETE /v2/source_maps/{id}", "DELETE /v2/sources/{id}", "DELETE /v2/status_page_incidents/{id}", "DELETE /v2/status_pages/{id}", @@ -219,6 +220,7 @@ describe("MapleApiV2 OpenAPI", () => { "GET /v2/slos/{id}", "GET /v2/slos/{id}/history", "GET /v2/slos/{id}/status", + "GET /v2/source_maps", "GET /v2/sources", "GET /v2/sources/usage", "GET /v2/sources/{id}", @@ -352,6 +354,7 @@ describe("MapleApiV2 OpenAPI", () => { "POST /v2/share/resolve", "POST /v2/share/widget-data", "POST /v2/slos", + "POST /v2/source_maps", "POST /v2/sources", "POST /v2/sources/{id}/pause", "POST /v2/sources/{id}/resume", diff --git a/packages/domain/src/http/v2/public-id.ts b/packages/domain/src/http/v2/public-id.ts index ee485564c7..54a85a294f 100644 --- a/packages/domain/src/http/v2/public-id.ts +++ b/packages/domain/src/http/v2/public-id.ts @@ -68,6 +68,7 @@ export const PublicIdPrefixes = { mcpConnection: "mcpc", deviceCredential: "dcred", dataSource: "dsrc", + sourceMap: "smap", /** Synthetic identity for logs, which have no native OTel record id. */ log: "log", /** Reserved for the future events/webhooks system. */ diff --git a/packages/domain/src/http/v2/source-maps.ts b/packages/domain/src/http/v2/source-maps.ts new file mode 100644 index 0000000000..58c12dcb67 --- /dev/null +++ b/packages/domain/src/http/v2/source-maps.ts @@ -0,0 +1,192 @@ +import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from "effect/http-api" +import { Schema } from "effect" +import { SourceMapFileId } from "@maple/primitives" +import { + SourceMapInvalidError, + SourceMapNotFoundError, + SourceMapStorageError, + SourceMapTooLargeError, +} from "../source-maps" +import { AuthorizationV2 } from "./auth" +import { wireExample, ListOf, ListQuery, Timestamp } from "./envelopes" +import { V2InsufficientPermissions, V2ParameterInvalid } from "./errors" +import { publicErrors } from "./public-error" +import { PublicId, PublicIdPrefixes } from "./public-id" + +/** `smap_…` public ID ⇄ internal `SourceMapFileId` (raw UUID). */ +export const SourceMapPublicId = PublicId(PublicIdPrefixes.sourceMap, SourceMapFileId) + +const DebugId = Schema.String.check(Schema.isGUID()).annotate({ + description: + "The file's debug id, as `maple sourcemaps inject` (or a bundler plugin) wrote it into the JavaScript file and its map.", + examples: ["6c5e2b1a-1f2e-4d3c-8b7a-0123456789ab"], +}) + +const Label = Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(256)) + +const sourceMapExample = { + object: "source_map", + id: "smap_YofPTrK9782DWwcnXhpcCw", + debug_id: "6c5e2b1a-1f2e-4d3c-8b7a-0123456789ab", + service: "web", + version: "1.4.2", + minified_path: "assets/index-Bx81.js", + size_bytes: 482113, + has_sources_content: true, + created_at: "2026-11-24T12:00:00.000Z", + last_used_at: null, +} as const + +export const V2SourceMap = Schema.Struct({ + object: Schema.Literal("source_map").annotate({ + description: 'The object type, always `"source_map"`.', + examples: ["source_map"], + }), + id: SourceMapPublicId, + debug_id: Schema.NullOr(DebugId), + service: Schema.NullOr(Schema.String).annotate({ + description: "The service the map was uploaded for, or `null` when matched by debug id only.", + examples: ["web"], + }), + version: Schema.NullOr(Schema.String).annotate({ + description: "The release (`service.version`) the map was uploaded for, or `null`.", + examples: ["1.4.2"], + }), + minified_path: Schema.String.annotate({ + description: + "Path of the JavaScript file the map belongs to, relative to the deploy root. A stack frame URL matches it when the URL's path equals it or ends with `/` followed by it, so `assets/app.js` matches `https://cdn.example.com/static/assets/app.js` but `app.js` does not match `assets/myapp.js`.", + examples: ["assets/index-Bx81.js"], + }), + size_bytes: Schema.Number.annotate({ + description: "Size of the stored map in bytes.", + examples: [482113], + }), + has_sources_content: Schema.Boolean.annotate({ + description: + "Whether the map embeds the original sources, which lets errors show code around each frame.", + examples: [true], + }), + created_at: Timestamp.annotate({ description: "When the map was uploaded." }), + last_used_at: Schema.NullOr(Timestamp).annotate({ + description: + "When the map last resolved a stack trace, to the day, or `null`. Maps unused for 90 days are deleted.", + }), +}).annotate({ + identifier: "SourceMap", + title: "Source Map", + description: + "A JavaScript source map Maple uses to turn minified browser stack traces back into your original code. Matched to a stack frame by debug id, else by service, version and file path.", + examples: [wireExample(sourceMapExample)], +}) +export type V2SourceMap = Schema.Schema.Type + +export const V2SourceMapUploadQuery = Schema.Struct({ + minified_path: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(1024)).annotate({ + description: + "Path of the JavaScript file the map belongs to, relative to the deploy root, such as `assets/index-Bx81.js`.", + examples: ["assets/index-Bx81.js"], + }), + debug_id: Schema.optional(DebugId), + service: Schema.optional( + Label.annotate({ + description: "The service the JavaScript belongs to (OTel `service.name`).", + examples: ["web"], + }), + ), + version: Schema.optional( + Label.annotate({ + description: "The release the JavaScript belongs to (OTel `service.version`).", + examples: ["1.4.2"], + }), + ), +}).annotate({ + identifier: "SourceMapUploadQuery", + title: "Source map upload parameters", + description: "Identify the uploaded map with `debug_id`, or with both `service` and `version`.", +}) +export type V2SourceMapUploadQuery = Schema.Schema.Type + +export const V2SourceMapListQuery = Schema.Struct({ + ...ListQuery.fields, + service: Schema.optional(Label), + version: Schema.optional(Label), + debug_id: Schema.optional(DebugId), +}).annotate({ + identifier: "SourceMapListQuery", + title: "Source map list query", + description: "Pagination plus optional filters on service, version and debug id.", +}) +export type V2SourceMapListQuery = Schema.Schema.Type + +/** The raw map bytes, sent as either content type. */ +const SourceMapBody = [ + Schema.Uint8Array.pipe(HttpApiSchema.asUint8Array({ contentType: "application/octet-stream" })), + Schema.Uint8Array.pipe(HttpApiSchema.asUint8Array({ contentType: "application/json" })), +] as const + +const SourceMapList = ListOf(V2SourceMap).annotate({ + identifier: "SourceMapList", + title: "Source map list", + description: "A cursor-paginated page of source maps.", +}) + +const [sourceMapInvalid, sourceMapTooLarge, sourceMapNotFound, sourceMapStorage] = publicErrors( + SourceMapInvalidError, + SourceMapTooLargeError, + SourceMapNotFoundError, + SourceMapStorageError, +) + +export class V2SourceMapsApiGroup extends HttpApiGroup.make("sourceMaps") + .add( + HttpApiEndpoint.post("upload", "/", { + query: V2SourceMapUploadQuery, + payload: SourceMapBody, + success: V2SourceMap, + error: [V2InsufficientPermissions.schema, sourceMapInvalid, sourceMapTooLarge, sourceMapStorage], + }).annotateMerge( + OpenApi.annotations({ + identifier: "uploadSourceMap", + summary: "Upload a source map", + description: + "Stores one source map (the raw JSON as the request body, at most 10 MiB, the largest map Maple can symbolicate with; larger is a 413). Index maps (with `sections`) are refused with a 400; emit a regular map. With a `debug_id`, only the map with that `debug_id` is replaced, so builds sharing a release path keep their own maps. Without one, the map without a debug id at the same `service`, `version` and `minified_path` is replaced. Requires an engineer or admin role and the `source_maps:write` scope.", + }), + ), + ) + .add( + HttpApiEndpoint.get("list", "/", { + query: V2SourceMapListQuery, + success: SourceMapList, + error: [V2ParameterInvalid.schema, sourceMapStorage], + }).annotateMerge( + OpenApi.annotations({ + identifier: "listSourceMaps", + summary: "List source maps", + description: + "Returns your organization's source maps, newest first. Cursor-paginated. Requires the `source_maps:read` scope.", + }), + ), + ) + .add( + HttpApiEndpoint.delete("delete", "/:id", { + params: { id: SourceMapPublicId }, + success: V2SourceMap, + error: [V2InsufficientPermissions.schema, sourceMapNotFound, sourceMapStorage], + }).annotateMerge( + OpenApi.annotations({ + identifier: "deleteSourceMap", + summary: "Delete a source map", + description: + "Deletes a source map and returns it as it was. Requires an engineer or admin role and the `source_maps:write` scope.", + }), + ), + ) + .prefix("/v2/source_maps") + .middleware(AuthorizationV2) + .annotateMerge( + OpenApi.annotations({ + title: "Source Maps", + description: + "JavaScript source maps for symbolicating browser errors. Upload one per built file from CI (`maple sourcemaps upload`), list them, or delete them. Any member may list; uploading and deleting take an engineer or admin.", + }), + ) {} diff --git a/packages/domain/src/org-erasure.ts b/packages/domain/src/org-erasure.ts index b10a855e1c..f12bec8b4f 100644 --- a/packages/domain/src/org-erasure.ts +++ b/packages/domain/src/org-erasure.ts @@ -2,8 +2,8 @@ import { Schema } from "effect" /** * What a deleted organization left outside Postgres, one kind per store: a `chat_session` is one - * agent conversation's Durable Object, `replay_blobs` the org's session-replay objects, and - * `warehouse` its rows in one warehouse datasource. + * agent conversation's Durable Object, `replay_blobs` the org's session-replay objects, + * `source_maps` its uploaded source map objects, and `warehouse` its rows in one warehouse datasource. */ -export const OrgErasureKind = Schema.Literals(["chat_session", "replay_blobs", "warehouse"]) +export const OrgErasureKind = Schema.Literals(["chat_session", "replay_blobs", "source_maps", "warehouse"]) export type OrgErasureKind = typeof OrgErasureKind.Type diff --git a/packages/domain/src/policy/api-key-scopes.ts b/packages/domain/src/policy/api-key-scopes.ts index 8c6d0430d1..0839b06ed8 100644 --- a/packages/domain/src/policy/api-key-scopes.ts +++ b/packages/domain/src/policy/api-key-scopes.ts @@ -24,6 +24,7 @@ export const apiKeyScopeFamilies = [ { id: "error_issues", label: "Errors", write: "error_issues:triage" }, { id: "anomalies", label: "Anomalies", write: "anomalies:configure" }, { id: "session_replays", label: "Session replays" }, + { id: "source_maps", label: "Source maps", write: "source_maps:upload" }, { id: "traces", label: "Traces" }, { id: "logs", label: "Logs" }, { id: "metrics", label: "Metrics" }, diff --git a/packages/domain/src/policy/permissions.ts b/packages/domain/src/policy/permissions.ts index 57b0e8baa2..4e0a36da6e 100644 --- a/packages/domain/src/policy/permissions.ts +++ b/packages/domain/src/policy/permissions.ts @@ -36,6 +36,7 @@ export const permissions = { "ai_triage:configure": { min: "engineer", action: "manage AI triage settings" }, "security:manage": { min: "engineer", action: "open the Security Center and triage its findings" }, "ingest_keys:roll": { min: "engineer", action: "roll ingest keys" }, + "source_maps:upload": { min: "engineer", action: "upload and delete source maps" }, "status_pages:access": { min: "engineer", action: "change who can view status pages" }, "data_sources:manage": { min: "engineer", action: "connect and manage data sources" }, // A query runs on the org's own database, so it takes the role that may connect one. diff --git a/packages/domain/src/tinybird/grouping.test.ts b/packages/domain/src/tinybird/grouping.test.ts index c01baff10b..ac9bbed4f2 100644 --- a/packages/domain/src/tinybird/grouping.test.ts +++ b/packages/domain/src/tinybird/grouping.test.ts @@ -1,8 +1,15 @@ import { Array as Arr, String as Str } from "effect" import { describe, expect, it } from "vitest" +import type { StackFrame, SymbolicatedStack } from "../errors/js-stack" import { explainGrouping, groupingKey, groupingParts, type GroupingSample } from "./grouping" -import { compileGroupingRules, GroupingConfig, groupingConfigDigest, OrgGroupingRule } from "./grouping-rules" +import { + compileGroupingRules, + GroupingConfig, + groupingConfigDigest, + OrgGroupingRule, + stableHash, +} from "./grouping-rules" const node = ( type: string, @@ -211,3 +218,276 @@ describe("org grouping rules", () => { expect(groupingConfigDigest(new GroupingConfig({ rules: [] }))).toBe("") }) }) + +describe("source-mapped frames", () => { + const unresolvedFrame = (raw: string): StackFrame => ({ + raw, + function: null, + file: null, + line: null, + column: null, + in_app: true, + resolved: false, + context: null, + }) + const mappedFrame = (raw: string, fn: string | null, file: string): StackFrame => ({ + raw, + function: fn, + function_from_map: fn !== null, + file, + line: 12, + column: 4, + in_app: !Str.includes("node_modules/")(file), + resolved: true, + context: null, + }) + const stackOf = (frames: ReadonlyArray): SymbolicatedStack => { + const resolved = Arr.filter(frames, (frame) => frame.resolved).length + return { + status: resolved === 0 ? "missing_map" : resolved === frames.length ? "resolved" : "partial", + frames, + missing: [], + } + } + const withStack = (sample: GroupingSample, frames: ReadonlyArray): GroupingSample => ({ + ...sample, + symbolicatedStack: stackOf(frames), + }) + + it("keeps today's key when the lookup resolves nothing", () => { + const fixtures: ReadonlyArray = [ + node("TypeError", "Cannot read properties of undefined", [ + "a (https://app.example/assets/index-Bx81.js:1:4410)", + ]), + node("StoreVaultError", "", [ + "credentialsVault.forwardStore (worker-app-sOddjqIe.js:2465:204564)", + ]), + node("SiteUnavailable", "Site is unavailable under current access", [ + "Hr (dist/ssr/assets/portal-native-resource-projection-VejMLjva.js:1104:1732)", + ]), + { + serviceName: "api", + exceptionType: "Error", + statusMessage: "", + exceptionStacktrace: "Error\n at handle (/app/backend/src/server.ts:41:9)", + }, + ] + Arr.forEach(fixtures, (sample) => { + const frames = Arr.map( + Arr.filter(Str.split("\n")(sample.exceptionStacktrace), (line) => Str.includes(" at ")(line)), + unresolvedFrame, + ) + const missing = withStack(sample, frames) + const notApplicable: GroupingSample = { + ...sample, + symbolicatedStack: { status: "not_applicable", frames, missing: [] }, + } + // Mapped, but only into a dependency: no app frame to key on. + const libraryOnly = withStack( + sample, + Arr.map(frames, (frame) => mappedFrame(frame.raw, "request", "node_modules/ky/index.js")), + ) + expect(groupingKey(missing)).toBe(groupingKey(sample)) + expect(groupingKey(notApplicable)).toBe(groupingKey(sample)) + expect(groupingKey(libraryOnly)).toBe(groupingKey(sample)) + expect(groupingParts(missing).rule).toBe(groupingParts(sample).rule) + }) + }) + + it("keys a generic error on original files and functions, never lines", () => { + const release = (bundle: string, minified: string, line: number) => { + const raw = `at ${minified} (https://app.example/assets/${bundle}.js:1:${line})` + const sample = node("TypeError", "Cannot read properties of undefined", [ + `${minified} (https://app.example/assets/${bundle}.js:1:${line})`, + ]) + return withStack(sample, [ + { ...mappedFrame(raw, "renderInvoice", "src/invoice.ts"), line, column: line }, + ]) + } + const v1 = release("index-Bx81", "a", 100) + const v2 = release("index-Qz07", "xe", 2000) + expect(groupingKey(stripStack(v1))).not.toBe(groupingKey(stripStack(v2))) + expect(groupingKey(v1)).toBe(groupingKey(v2)) + const why = explainGrouping(v1) + expect(why.rule).toBe("source-mapped") + expect(why.frames).toEqual(["at renderInvoice (src/invoice.ts)"]) + }) + + it("keeps the rules above frames in front: custom keys, org merges, chunk loads, type and message", () => { + const frames = [ + mappedFrame("at a (https://app.example/a-1.js:1:1)", "renderInvoice", "src/invoice.ts"), + ] + const custom = withStack(node("TypeError", "boom", ["a (https://app.example/a-1.js:1:1)"]), frames) + const keyed = { ...custom, customFingerprint: "invoice" } + expect(groupingParts(keyed).rule).toBe("custom") + const extended = { ...custom, customFingerprint: "{{default}} tenant-a" } + expect(groupingParts(extended).parts).toContain("tenant-a") + expect(groupingParts(extended).rule).toBe("source-mapped") + + const merge = compileGroupingRules( + new GroupingConfig({ + rules: [new OrgGroupingRule({ id: "booms", kind: "merge", message: "boom" })], + }), + ) + expect(groupingParts(custom, merge).rule).toBe("org-rule") + + const chunk = withStack( + node("TypeError", "Failed to fetch dynamically imported module: https://app.example/a-1.js", []), + frames, + ) + expect(groupingParts(chunk).rule).toBe("chunk-load") + + const tagged = withStack( + node("InvoiceMissing", "no invoice", ["a (https://app.example/a-1.js:1:1)"]), + frames, + ) + expect(groupingParts(tagged).rule).toBe("type-message") + expect(groupingKey(tagged)).toBe(groupingKey(stripStack(tagged))) + }) + + it("tells unnamed throw sites in one file apart by their source line, not its number", () => { + const site = (bundle: string, minified: string, line: number, text: string | null) => { + const raw = `at ${minified} (https://app.example/assets/${bundle}.js:1:${line})` + const sample = node("TypeError", "Cannot read properties of undefined (reading 'total')", [ + `${minified} (https://app.example/assets/${bundle}.js:1:${line})`, + ]) + // No caller names the frame, so it keeps its minified name. + return withStack(sample, [ + { + ...mappedFrame(raw, minified, "src/checkout.ts"), + function_from_map: false, + line, + context: text === null ? null : { pre: [], line: text, post: [] }, + }, + ]) + } + const invoice = site("index-Bx81", "a", 40, " return invoice.total") + const payment = site("index-Bx81", "b", 90, " return payment.total") + expect(groupingKey(invoice)).not.toBe(groupingKey(payment)) + expect(explainGrouping(invoice).frames).toEqual(["at src/checkout.ts | return invoice.total"]) + + // The same throw site after a deploy: new bundle, new minified name, lines moved. + const invoiceNext = site("index-Qz07", "xe", 52, "\treturn invoice.total ") + expect(groupingKey(invoiceNext)).toBe(groupingKey(invoice)) + + // With neither a name nor source text, the mapped key would be the file alone: raw key instead. + const bare = site("index-Bx81", "a", 40, null) + expect(groupingKey(bare)).toBe(groupingKey(stripStack(bare))) + expect(groupingParts(bare).rule).toBe("frames") + }) + + it("keys a source line on its text with only the ends trimmed", () => { + const site = (text: string) => + withStack(node("TypeError", "boom", ["a (https://app.example/assets/x.js:1:9)"]), [ + { + ...mappedFrame("at a (https://app.example/assets/x.js:1:9)", "a", "src/totals.ts"), + function_from_map: false, + context: { pre: [], line: text, post: [] }, + }, + ]) + expect(groupingKey(site(' totals["tax rate"].total'))).not.toBe( + groupingKey(site('totals["tax rate"].total')), + ) + expect(groupingKey(site("x.split(/a b/)"))).not.toBe(groupingKey(site("x.split(/a b/)"))) + expect(groupingKey(site('\ttotals["tax rate"].total '))).toBe( + groupingKey(site('totals["tax rate"].total')), + ) + }) + + it("applies a frame rule on the generated file to the frame after its map resolves it", () => { + const vendor = compileGroupingRules( + new GroupingConfig({ + rules: [ + new OrgGroupingRule({ id: "vendor", kind: "library-frames", frame: "*vendor-*.js*" }), + ], + }), + ) + const frames = [ + "wrap (https://app.example/assets/vendor-9f.js:1:5)", + "renderInvoice (https://app.example/assets/index-1.js:1:9)", + ] + const sample = node("TypeError", "boom", frames) + const mapped = withStack(sample, [ + mappedFrame(`at ${frames[0] ?? ""}`, "wrap", "src/wrapper.ts"), + mappedFrame(`at ${frames[1] ?? ""}`, "renderInvoice", "src/invoice.ts"), + ]) + expect(explainGrouping(stripStack(sample), vendor).skippedFrames).toHaveLength(1) + const why = explainGrouping(mapped, vendor) + expect(why.frames).toEqual(["at renderInvoice (src/invoice.ts)"]) + expect(why.skippedFrames).toEqual(["at wrap (src/wrapper.ts)"]) + }) + + it("keeps the raw key when the throw site did not map, though its caller did", () => { + const site = (bundle: string) => { + const top = `t (https://app.example/assets/${bundle}.js:1:1)` + const caller = "a (https://app.example/assets/index-1.js:1:9)" + return withStack(node("TypeError", "boom", [top, caller]), [ + { ...unresolvedFrame(`at ${top}`), file: `https://app.example/assets/${bundle}.js` }, + mappedFrame(`at ${caller}`, "dispatch", "src/dispatch.ts"), + ]) + } + expect(groupingParts(site("one")).rule).toBe("frames") + expect(groupingKey(site("one"))).toBe(groupingKey(stripStack(site("one")))) + expect(groupingKey(site("one"))).not.toBe(groupingKey(site("two"))) + }) + + it("treats an unmapped frame an app rule claims as the throw site", () => { + const generated = compileGroupingRules( + new GroupingConfig({ + rules: [ + new OrgGroupingRule({ id: "ours", kind: "app-frames", frame: "*node_modules/@acme/*" }), + ], + }), + ) + const site = (bundle: string) => { + const top = `t (https://app.example/node_modules/@acme/ui/${bundle}.js:1:1)` + const caller = "a (https://app.example/assets/index-1.js:1:9)" + return withStack(node("TypeError", "boom", [top, caller]), [ + { ...unresolvedFrame(`at ${top}`), in_app: false }, + mappedFrame(`at ${caller}`, "dispatch", "src/dispatch.ts"), + ]) + } + expect(groupingParts(site("one"), generated).rule).toBe("frames") + expect(groupingKey(site("one"), generated)).not.toBe(groupingKey(site("two"), generated)) + }) + + it("keeps a map-supplied name that happens to equal the generated one", () => { + const release = (bundle: string, generated: string) => + withStack(node("TypeError", "boom", [`${generated} (https://app.example/${bundle}.js:1:9)`]), [ + mappedFrame( + `at ${generated} (https://app.example/${bundle}.js:1:9)`, + "renderInvoice", + "src/invoice.ts", + ), + ]) + // An unminified build keeps the original name; a minified one renames it. Both map to it. + expect(groupingKey(release("plain", "renderInvoice"))).toBe(groupingKey(release("min", "a"))) + expect(explainGrouping(release("plain", "renderInvoice")).frames).toEqual([ + "at renderInvoice (src/invoice.ts)", + ]) + }) + + it("keys a tagged error with no message on the original function", () => { + const raw = (name: string, bundle: string) => `at ${name} (https://app.example/${bundle}.js:1:9)` + const v1 = withStack(node("StoreVaultError", "", [`Hr (https://app.example/w-1.js:1:9)`]), [ + mappedFrame(raw("Hr", "w-1"), "forwardStore", "src/vault.ts"), + ]) + const v2 = withStack(node("StoreVaultError", "", [`Tq (https://app.example/w-2.js:1:9)`]), [ + mappedFrame(raw("Tq", "w-2"), "forwardStore", "src/vault.ts"), + ]) + const other = withStack(node("StoreVaultError", "", [`Tq (https://app.example/w-2.js:1:9)`]), [ + mappedFrame(raw("Tq", "w-2"), "readStore", "src/vault.ts"), + ]) + expect(groupingParts(v1).rule).toBe("source-mapped-function") + expect(explainGrouping(v1).frames).toEqual(["at forwardStore (src/vault.ts)"]) + expect(groupingKey(v1)).toBe(groupingKey(v2)) + expect(groupingKey(v1)).not.toBe(groupingKey(other)) + // The key still hashes the rule as `source-mapped`, as it did before the rule had its own + // name, so no stored key changes. + expect(groupingKey(v1)).toBe( + stableHash(Arr.join(["g1", "api", "source-mapped", "StoreVaultError", "forwardStore"], "\u0000")), + ) + }) +}) + +const stripStack = ({ symbolicatedStack: _stack, ...sample }: GroupingSample): GroupingSample => sample diff --git a/packages/domain/src/tinybird/grouping.ts b/packages/domain/src/tinybird/grouping.ts index 303157004f..209e5ce4e7 100644 --- a/packages/domain/src/tinybird/grouping.ts +++ b/packages/domain/src/tinybird/grouping.ts @@ -3,14 +3,16 @@ * from one sample. Keys only merge hashes, never split one; why and how it was measured is * in `docs/error-issue-lifecycle.md` ("The grouping key"). */ -import { Array as Arr, Schema, String as Str } from "effect" +import { Array as Arr, Option, Schema, String as Str } from "effect" +import type { StackFrame, SymbolicatedStack } from "../errors/js-stack" import { computeFingerprintInputs, currentFrameCandidates, CUSTOM_FINGERPRINT_ATTRIBUTE, type FingerprintInputs, isLibraryFrame, + MAX_FINGERPRINT_FRAMES, SPAN_SIGNATURE_PREFIX, } from "./fingerprint" import { @@ -65,6 +67,10 @@ const framePathRe = /(\(|@|^[ \t]*at |^[ \t]*File ")(?:[^ ()"]*\/)?([^/ ()"]+\/[ * - `type-message`: a specific error type with a message; the two are the identity. * - `type-function`: a specific error type with no message; the first named function. * - `frames`: a generic type; frames (install roots trimmed) and message, as the hash. + * - `source-mapped`: `frames` read through source maps: original files and functions, so a + * deploy's renamed bundle keeps its key. + * - `source-mapped-function`: `type-function` read through source maps: the type and the first + * mapped function. Keyed as `source-mapped` (see `keyOfParts`), so the name changes no key. */ export const GroupingRule = Schema.Literals([ "custom", @@ -74,6 +80,8 @@ export const GroupingRule = Schema.Literals([ "type-message", "type-function", "frames", + "source-mapped", + "source-mapped-function", ]).annotate({ identifier: "@maple/GroupingRule", title: "Grouping Rule" }) export type GroupingRule = Schema.Schema.Type @@ -90,6 +98,8 @@ export interface GroupingSample { readonly statusMessage: string readonly customFingerprint?: string readonly span?: { readonly kind: string; readonly name: string } + /** The stack mapped through the org's source maps, when the tick could look it up. */ + readonly symbolicatedStack?: SymbolicatedStack } /** A frame's file, cut to its last two path segments: install roots and worktrees vary. */ @@ -106,6 +116,66 @@ export const frameFunction = (frame: string): string | undefined => { return name === undefined || plumbingRe.test(name) ? undefined : name } +/** A mapped frame's function when the source map supplied it, unless it is plumbing. */ +const mappedFunction = (frame: StackFrame): string | undefined => { + const name = frame.function + return frame.function_from_map !== true || name === null || plumbingRe.test(name) ? undefined : name +} + +/** + * A mapped frame as the key reads it, never a line or column: its original file and function, or, + * with no function name, the file and its source line's text. `undefined` when it has neither. + */ +const mappedFrameLine = (frame: StackFrame, file: string): string | undefined => { + const name = mappedFunction(frame) + if (name !== undefined) return `at ${name} (${file})` + // Only the ends are trimmed: inner whitespace can be code (a string or regex literal). + const text = frame.context === null ? "" : Str.trim(frame.context.line) + return text === "" ? undefined : `at ${file} | ${text}` +} + +/** + * The app's source-mapped frames, top first, when the stack resolved at least one. Unmapped + * frames are left out: their names and hashed files change with every deploy. `undefined` also + * when a frame the key reads has no identity beyond its file: the raw key keeps it apart. + */ +const sourceMappedFrames = ( + sample: GroupingSample, + rules: CompiledGroupingRules, +): { readonly frames: ReadonlyArray; readonly skipped: ReadonlyArray } | undefined => { + const stack = sample.symbolicatedStack + if (stack === undefined || (stack.status !== "resolved" && stack.status !== "partial")) return undefined + // Rules read both the generated frame and its mapped location, as they did before the map + // came: a frame either side marks a library stays out of the key, one marked app is in. + const isApp = (frame: StackFrame, shown: string) => { + const kinds = [rules.frameKind(shown, sample), rules.frameKind(frame.raw, sample)] + return Arr.contains(kinds, "library") ? false : Arr.contains(kinds, "app") ? true : frame.in_app + } + // An unmapped throw site leaves only its callers: two throw sites could share them, so raw key. + const throwSite = Arr.findFirst(stack.frames, (frame) => isApp(frame, frame.raw)) + if (Option.isSome(throwSite) && !throwSite.value.resolved) return undefined + const mapped = Arr.dedupeAdjacentWith( + Arr.flatMap(stack.frames, (frame) => { + if (!frame.resolved || frame.file === null) return [] + const line = mappedFrameLine(frame, frame.file) + const shown = line ?? `at ${frame.file}` + return [{ line, shown, app: isApp(frame, shown) }] + }), + (a, b) => a.line !== undefined && a.line === b.line, + ) + const read = Arr.filter(mapped, (frame) => frame.app).slice(0, MAX_FINGERPRINT_FRAMES) + if (read.length === 0) return undefined + const lines = Arr.getSomes(Arr.map(read, (frame) => Option.fromUndefinedOr(frame.line))) + if (lines.length < read.length) return undefined + return { + frames: lines, + skipped: Arr.map( + Arr.filter(mapped, (frame) => !frame.app), + (frame) => frame.shown, + ), + } +} + /** A key's inputs, and what the "why grouped" view shows of them. */ export interface GroupingExplanation extends GroupingParts { /** The frames the rule read, top first; empty when it reads none. */ @@ -150,10 +220,15 @@ export const explainGrouping = ( sample.customFingerprint === undefined || Str.trim(sample.customFingerprint) === "" ? undefined : Str.trim(sample.customFingerprint) - const explained = (parts: GroupingParts, read: ReadonlyArray, orgRule?: OrgGroupingRule) => ({ + const explained = ( + parts: GroupingParts, + read: ReadonlyArray, + orgRule?: OrgGroupingRule, + passedOver: ReadonlyArray = skipped, + ) => ({ ...parts, frames: read, - skippedFrames: read.length === 0 ? [] : skipped, + skippedFrames: read.length === 0 ? [] : passedOver, messageSignature: inputs.msgSignature, customKey, orgRule, @@ -180,11 +255,36 @@ export const explainGrouping = ( } const message = inputs.msgSignature const trimmed = Arr.join(Arr.map(frames, trimFramePath), "\n") + // Only the frame parts read source maps; every rule above keeps its priority. + const mapped = sourceMappedFrames(sample, rules) const byFrames = () => - explained(extend({ rule: "frames", parts: [sample.exceptionType, trimmed, message] }), frames) + mapped === undefined + ? explained(extend({ rule: "frames", parts: [sample.exceptionType, trimmed, message] }), frames) + : explained( + extend({ + rule: "source-mapped", + parts: [sample.exceptionType, Arr.join(mapped.frames, "\n"), message], + }), + mapped.frames, + undefined, + mapped.skipped, + ) if (genericTypeRe.test(sample.exceptionType)) return byFrames() if (message !== "") return explained(extend({ rule: "type-message", parts: [sample.exceptionType, message] }), []) + if (mapped !== undefined) { + const mappedNamed = Arr.findFirst(mapped.frames, (frame) => frameFunction(frame) !== undefined) + if (mappedNamed._tag === "None") return byFrames() + return explained( + extend({ + rule: "source-mapped-function", + parts: [sample.exceptionType, frameFunction(mappedNamed.value) ?? ""], + }), + [mappedNamed.value], + undefined, + mapped.skipped, + ) + } const named = Arr.findFirst(frames, (frame) => frameFunction(frame) !== undefined) if (named._tag === "None") return byFrames() return explained( @@ -203,7 +303,14 @@ export const groupingParts = ( /** The stored key for a service and its parts, as `groupingKey` computes it. */ export const keyOfParts = (serviceName: string, { rule, parts }: GroupingParts): string => - stableHash(Arr.join([`g${GROUPING_KEY_VERSION}`, serviceName, rule, ...parts], "\u0000")) + stableHash(Arr.join([`g${GROUPING_KEY_VERSION}`, serviceName, keyedRule(rule), ...parts], "\u0000")) + +/** + * The rule as the key hashes it. `source-mapped-function` was keyed as `source-mapped` before it had + * its own name, so it still is: a stored key never changes for a rename. + */ +const keyedRule = (rule: GroupingRule): GroupingRule => + rule === "source-mapped-function" ? "source-mapped" : rule /** The key two hashes must share to join one issue. Scoped to the service, as the hash is. */ export const groupingKey = (sample: GroupingSample, rules: CompiledGroupingRules = NO_RULES): string => diff --git a/packages/infra/package.json b/packages/infra/package.json index 8714fcf839..f6baf146fc 100644 --- a/packages/infra/package.json +++ b/packages/infra/package.json @@ -20,6 +20,7 @@ "./secret-slot-keys": "./src/secret-slot-keys.ts", "./secrets": "./src/secrets.ts", "./security-baseline": "./src/aws/security-baseline.ts", + "./self-source-maps": "./src/cloudflare/self-source-maps.ts", "./worker-build": "./src/cloudflare/worker-build.ts", "./worker-runtime": "./src/cloudflare/worker-runtime.ts", "./worker-telemetry": "./src/cloudflare/worker-telemetry.ts", diff --git a/packages/infra/src/cloudflare/index.ts b/packages/infra/src/cloudflare/index.ts index d0b34a5bf5..39939a0a26 100644 --- a/packages/infra/src/cloudflare/index.ts +++ b/packages/infra/src/cloudflare/index.ts @@ -6,6 +6,7 @@ export * from "./status-pages.ts" export * from "./maple-db.ts" export * from "./observability.ts" export * from "./replay-blobs.ts" +export * from "./source-maps.ts" export * from "./stack.ts" export * from "./stage.ts" export * from "../region.ts" diff --git a/packages/infra/src/cloudflare/self-source-maps.ts b/packages/infra/src/cloudflare/self-source-maps.ts new file mode 100644 index 0000000000..1622030d0c --- /dev/null +++ b/packages/infra/src/cloudflare/self-source-maps.ts @@ -0,0 +1,51 @@ +// The dashboard's own source maps, uploaded into Maple's org after each prd build of `web`. +import * as Maple from "@maple-dev/alchemy" +import { Effect, Layer, Option, Redacted } from "effect" +import { FetchHttpClient } from "effect/http" +import { commitSha } from "../env.ts" +import { resolveAs } from "../secret-guard.ts" +import { MapleSourceMapsApiKey } from "../secrets.ts" + +/** The deploy's read of the upload key: absent outside prd, where nothing uploads. */ +export const webSourceMapsApiKey = MapleSourceMapsApiKey.optionalValue + +/** + * Maple's providers on the upload key. Without one the key is empty and no `Maple.*` resource is + * declared, so the client is never called. + */ +export const selfMapleProviders = Maple.providersWithDependencies().pipe( + Layer.provide(FetchHttpClient.layer), + Layer.provide( + Layer.effect( + Maple.MapleEnvironment, + Effect.map(resolveAs("web", webSourceMapsApiKey), (key) => ({ + baseUrl: Maple.DEFAULT_BASE_URL, + apiKey: Option.getOrElse(key, () => Redacted.make("")), + })), + ).pipe(Layer.orDie), + ), +) + +/** + * Uploads web's maps from `dir` under the service and release its browser telemetry reports + * (`service.version` is `VITE_COMMIT_SHA`, resolved here as `web`'s env resolves it). A no-op + * without the key. + */ +export const uploadWebSourceMaps = (input: { + readonly dir: string + readonly service: string + readonly after: unknown +}) => + Effect.gen(function* () { + const key = yield* resolveAs("web", webSourceMapsApiKey) + if (Option.isNone(key)) return + const release = yield* commitSha("VITE_COMMIT_SHA") + yield* Maple.SourceMaps("web-sourcemaps", { + dir: input.dir, + service: input.service, + ...(release === "" ? undefined : { release }), + // web's telemetry reports no debug ids: each release keeps its own id-less maps. + matchBy: "release", + after: input.after, + }) + }) diff --git a/packages/infra/src/cloudflare/source-maps.ts b/packages/infra/src/cloudflare/source-maps.ts new file mode 100644 index 0000000000..2c23d67b97 --- /dev/null +++ b/packages/infra/src/cloudflare/source-maps.ts @@ -0,0 +1,21 @@ +/** + * Uploaded JavaScript source maps, one object per file at `v1//`. The api writes + * and reads them, the alerting Worker reads them (read-only) to group errors on mapped frames, and + * the org-eraser Worker deletes a deleted org's prefix. Stage-isolated. + * No lifecycle rule: retention is by last use, swept in code with the `source_map_files` rows. + * Never add or change `locationHint` or `jurisdiction`: either replaces the + * name-pinned bucket, which GC then deletes. Colocation needs a new bucket. + */ +import { REGION_INFRA } from "../region.ts" +import { stageProps } from "./stack.ts" +import * as Cloudflare from "@alchemy.run/cloudflare" +import * as RemovalPolicy from "alchemy/RemovalPolicy" + +export const SourceMapsBucket = Cloudflare.R2.Bucket( + "source-maps", + stageProps("source-maps", (name, { region }) => ({ + name, + jurisdiction: REGION_INFRA[region].storageJurisdiction, + })), + // Customer uploads: `retain` never physically deletes a replaced generation. +).pipe(RemovalPolicy.retain()) diff --git a/packages/infra/src/secrets.ts b/packages/infra/src/secrets.ts index b058c42fab..e3a7af2fdb 100644 --- a/packages/infra/src/secrets.ts +++ b/packages/infra/src/secrets.ts @@ -158,6 +158,14 @@ export class OtelIngestKey extends Secret()("MAPLE_OTEL_INGEST_KE sharesProdValueWith: ["dev", "preview"], }) {} +// Uploads the dashboard's source maps into Maple's own org at deploy (`source_maps:write` only). Prd +// alone: dev and preview builds upload nothing. +export class MapleSourceMapsApiKey extends Secret()("MAPLE_SOURCEMAPS_API_KEY", { + issuer: "maple", + consumers: ["web"], + environments: PRD_ONLY, +}) {} + export class ProductEventsIngestKey extends Secret()( "MAPLE_PRODUCT_EVENTS_INGEST_KEY", // ai and alerting stamp an org's first data, which emits `first_data_received`. diff --git a/packages/primitives/src/index.ts b/packages/primitives/src/index.ts index 6b5b219a09..9ef3256a50 100644 --- a/packages/primitives/src/index.ts +++ b/packages/primitives/src/index.ts @@ -486,6 +486,9 @@ export const IngestAttributeMappingId = MapleUuidId( ) export type IngestAttributeMappingId = Schema.Schema.Type +export const SourceMapFileId = MapleUuidId("@maple/SourceMapFileId", "Source Map File ID") +export type SourceMapFileId = Schema.Schema.Type + export const IngestMappingSourceContext = Schema.Literals(["span", "resource"]).annotate({ identifier: "@maple/IngestMappingSourceContext", title: "Ingest Mapping Source Context", diff --git a/packages/query-engine/src/__sql_baseline__/catalog.sql b/packages/query-engine/src/__sql_baseline__/catalog.sql index 3bf09cad3c..93bf48adfd 100644 --- a/packages/query-engine/src/__sql_baseline__/catalog.sql +++ b/packages/query-engine/src/__sql_baseline__/catalog.sql @@ -1617,10 +1617,11 @@ SELECT AND error_events.Timestamp <= '2026-01-03 14:15:00' FORMAT JSON --- builder:errors:errorGroupingSamplesQuery:default [025309cc] +-- builder:errors:errorGroupingSamplesQuery:default [90be06ec] SELECT toString(error_events.FingerprintHash) AS fingerprintHash, argMax(error_events.ServiceName, concat(toString(error_events.Timestamp), ' ', error_events.TraceId, ' ', error_events.SpanId)) AS serviceName, + argMax(error_events.ServiceVersion, concat(toString(error_events.Timestamp), ' ', error_events.TraceId, ' ', error_events.SpanId)) AS serviceVersion, max(error_events.Timestamp) AS timestamp, argMax(error_events.TraceId, concat(toString(error_events.Timestamp), ' ', error_events.TraceId, ' ', error_events.SpanId)) AS traceId, argMax(error_events.SpanId, concat(toString(error_events.Timestamp), ' ', error_events.TraceId, ' ', error_events.SpanId)) AS spanId, @@ -1668,10 +1669,14 @@ SELECT LIMIT 20 FORMAT JSON --- builder:errors:errorIssueLatestStacktraceQuery:default [5489bb6f] +-- builder:errors:errorIssueLatestStacktraceQuery:default [6cb41cd5] SELECT error_events.Timestamp AS timestamp, - error_events.ExceptionStacktrace AS stacktrace + error_events.ExceptionStacktrace AS stacktrace, + error_events.ServiceName AS serviceName, + error_events.ServiceVersion AS serviceVersion, + toString(error_events.TraceId) AS traceId, + toString(error_events.SpanId) AS spanId FROM error_events WHERE error_events.OrgId = 'org_sql_catalog' AND error_events.FingerprintHash IN (toUInt64('11640393269246331608')) diff --git a/packages/query-engine/src/ch/queries/errors.ts b/packages/query-engine/src/ch/queries/errors.ts index 14ee3e2b64..781c459b0d 100644 --- a/packages/query-engine/src/ch/queries/errors.ts +++ b/packages/query-engine/src/ch/queries/errors.ts @@ -1464,6 +1464,12 @@ export function errorIssueLatestStacktraceQuery(opts: IssueFingerprintsOpts) { .select(($) => ({ timestamp: $.Timestamp, stacktrace: $.ExceptionStacktrace, + // The span behind it, read for the exception event's debug ids, and the release a map can match. + serviceName: $.ServiceName, + serviceVersion: $.ServiceVersion, + // Plain strings: an occurrence can carry no trace or span, and ClickHouse returns ''. + traceId: CH.toString_($.TraceId), + spanId: CH.toString_($.SpanId), })) .where(($) => [ $.OrgId.eq(orgIdParam), @@ -1813,6 +1819,8 @@ export function errorGroupingSamplesQuery(opts: { readonly fingerprintHashes: re return { fingerprintHash: CH.toString_($.FingerprintHash), serviceName: CH.argMax($.ServiceName, latest), + // Matches source maps uploaded by service and version, for a stack's frames. + serviceVersion: CH.argMax($.ServiceVersion, latest), timestamp: CH.max_($.Timestamp), traceId: CH.argMax($.TraceId, latest), spanId: CH.argMax($.SpanId, latest), diff --git a/packages/sourcemaps/package.json b/packages/sourcemaps/package.json new file mode 100644 index 0000000000..7151a5c56f --- /dev/null +++ b/packages/sourcemaps/package.json @@ -0,0 +1,21 @@ +{ + "name": "@maple/sourcemaps", + "private": true, + "description": "Debug-id injection for built JavaScript and its source maps, shared by the Maple CLI and the Alchemy Vite plugin. Private: consumers bundle it.", + "type": "module", + "sideEffects": false, + "exports": { + ".": "./src/index.ts", + "./limits": "./src/limits.ts" + }, + "scripts": { + "typecheck": "tsrs --noEmit" + }, + "dependencies": { + "effect": "catalog:effect" + }, + "devDependencies": { + "@types/node": "catalog:tooling", + "typescript": "catalog:tooling" + } +} diff --git a/packages/sourcemaps/src/index.ts b/packages/sourcemaps/src/index.ts new file mode 100644 index 0000000000..aeb37ac5f0 --- /dev/null +++ b/packages/sourcemaps/src/index.ts @@ -0,0 +1,2 @@ +export * from "./inject.ts" +export * from "./relocate.ts" diff --git a/packages/sourcemaps/src/inject.ts b/packages/sourcemaps/src/inject.ts new file mode 100644 index 0000000000..29acd23b7a --- /dev/null +++ b/packages/sourcemaps/src/inject.ts @@ -0,0 +1,390 @@ +// Give built JS files a debug id derived from the file and its map, registered at runtime, so the +// backend can pick each file's source map by id. Shared by `maple sourcemaps` and the Vite plugin. + +import { createHash } from "node:crypto" +import { Array as Arr, Effect, Option, Order, Predicate, Result, Schema, String as Str } from "effect" +import { FileSystem } from "effect/FileSystem" +import { Path } from "effect/Path" + +export const JS_EXTENSIONS: ReadonlyArray = [".js", ".mjs", ".cjs"] + +/** Reading or writing the build output failed. */ +export class SourceMapsFileError extends Schema.TaggedError()( + "@maple/sourcemaps/SourceMapsFileError", + { + message: Schema.String, + path: Schema.String, + cause: Schema.optionalKey(Schema.Defect()), + }, +) {} + +// `\r?` before `$`: with the `m` flag `$` stops at `\n`, so CRLF files keep a `\r` there. +const DEBUG_ID_COMMENT = /^\/\/# debugId=([0-9a-fA-F-]{36})[ \t]*\r?$/m +const SOURCE_MAPPING_URL = /^\/\/[#@] sourceMappingURL=(\S+)[ \t]*\r?$/gm +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/ +const REGISTERED_ID = /_(?:maple|sentry)DebugIds\[[^\]]*\]\s*=\s*["']([0-9a-fA-F-]{36})["']/ + +const MapObject = Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)) +const decodeMap = Schema.decodeUnknownResult(MapObject) +const encodeMap = Schema.encodeResult(MapObject) + +/** The map as JSON without its `debugId` / `debug_id`, so writing an id never changes the hash. */ +const canonicalMap = (mapText: string): string => + Result.match(decodeMap(mapText), { + onFailure: () => mapText, + onSuccess: ({ debugId: _a, debug_id: _b, x_maple_shifted: _c, ...rest }) => + Result.getOrElse(encodeMap(rest), () => mapText), + }) + +/** + * sha256 of the JS file and its map as a lowercase UUID. The version (4) and variant nibbles are set + * so the id passes strict UUID validators; the rest is the hash, so the same build always gets the + * same id, and identical JS with another map (comments moved, sources changed) gets another. + */ +export const debugIdFor = (code: Uint8Array | string, mapText: string): string => { + const h = createHash("sha256").update(code).update("\u0000").update(canonicalMap(mapText)).digest("hex") + const part = (start: number, end: number) => Str.slice(start, end)(h) + const variant = ((Number.parseInt(part(16, 17), 16) & 0x3) | 0x8).toString(16) + return `${part(0, 8)}-${part(8, 12)}-4${part(13, 16)}-${variant}${part(17, 20)}-${part(20, 32)}` +} + +export const debugIdSnippet = (id: string): string => + `;!function(){try{var g="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},s=(new g.Error).stack;s&&(g._mapleDebugIds=g._mapleDebugIds||{},g._mapleDebugIds[s]="${id}")}catch(e){}}();` + +/** The id in an existing `//# debugId=` comment, else the one a runtime registration assigns. */ +export const existingDebugId = (code: string): Option.Option => + Option.firstSomeOf([ + Option.fromNullishOr(DEBUG_ID_COMMENT.exec(code)?.[1]), + Option.fromNullishOr(REGISTERED_ID.exec(code)?.[1]), + ]).pipe( + Option.map(Str.toLowerCase), + Option.filter((id) => UUID.test(id)), + ) + +/** The last `//# sourceMappingURL=` comment: its value and where its line starts. */ +export const sourceMappingUrl = ( + code: string, +): Option.Option<{ readonly url: string; readonly index: number }> => + Arr.last(Arr.fromIterable(Str.matchAll(SOURCE_MAPPING_URL)(code))).pipe( + Option.flatMap((match) => + Option.all({ url: Option.fromNullishOr(match[1]), index: Option.fromNullishOr(match.index) }), + ), + ) + +/** + * Whether the file registers `id` at runtime (ours or Sentry's snippet assigning it into the + * debug id map), which a bare `//# debugId=` comment does not. A bundled SDK that only reads + * the map does not count. `id` is a UUID, so it needs no escaping. + */ +export const hasRuntimeRegistration = (code: string, id: string): boolean => + new RegExp(`_(?:maple|sentry)DebugIds\\[[^\\]]*\\]\\s*=\\s*["']${id}["']`, "i").test(code) + +/** Where trailing comments start: the first of an existing debugId and the last sourceMappingURL. */ +const trailerIndex = (code: string): Option.Option => + Arr.head( + Arr.sort( + [ + ...Option.toArray(Option.fromNullishOr(DEBUG_ID_COMMENT.exec(code)?.index)), + ...Option.toArray(Option.map(sourceMappingUrl(code), (url) => url.index)), + ], + Order.Number, + ), + ) + +const insertBeforeTrailer = (code: string, block: string): string => + Option.match(trailerIndex(code), { + onSome: (index) => `${Str.slice(0, index)(code)}${block}${Str.slice(index)(code)}`, + onNone: () => `${code}${code === "" || Str.endsWith("\n")(code) ? "" : "\n"}${block}`, + }) + +/** + * Whether the snippet can go on a new first line: not above a shebang, and not above a directive + * prologue (`"use strict"` and the like), which only counts as one at the top. + */ +export const canPrepend = (code: string): boolean => !Str.startsWith("#!")(code) && !startsWithString(code) + +/** Whether the first token after whitespace and comments is a string literal; one linear pass. */ +const startsWithString = (code: string): boolean => { + const rest = Str.trimStart(code) + if (Str.startsWith("//")(rest)) { + return Option.match(Str.indexOf("\n")(rest), { + onNone: () => false, + onSome: (end) => startsWithString(Str.slice(end + 1)(rest)), + }) + } + if (Str.startsWith("/*")(rest)) { + return Option.match(Str.indexOf("*/")(Str.slice(2)(rest)), { + onNone: () => false, + onSome: (end) => startsWithString(Str.slice(end + 4)(rest)), + }) + } + return Str.startsWith('"')(rest) || Str.startsWith("'")(rest) +} + +/** + * `prepend`: the snippet on a new first line, so the id is registered before the module's own code + * runs (a throw while it loads still reports it); every line moves down one, which the map's + * mappings must follow (`shiftMappings`). `append`: the snippet after the code, before the trailing + * debugId / sourceMappingURL comments, so nothing moves. Either way the `//# debugId=` comment is + * added near the end unless the file has one. + */ +export const injectCode = (code: string, id: string, mode: "prepend" | "append"): string => { + const hasComment = DEBUG_ID_COMMENT.test(code) + if (mode === "prepend") { + const tagged = hasComment ? code : insertBeforeTrailer(code, `//# debugId=${id}\n`) + return `${debugIdSnippet(id)}\n${tagged}` + } + return insertBeforeTrailer( + code, + hasComment ? `${debugIdSnippet(id)}\n` : `${debugIdSnippet(id)}\n//# debugId=${id}\n`, + ) +} + +/** Mappings for code one line lower: an empty first generated line. */ +export const shiftMappings = (mappings: string): string => `;${mappings}` + +/** The map's own debug id (`debugId`, else `debug_id`), or `None` when it has none or is not JSON. */ +export const mapDebugId = (mapText: string): Option.Option => + Result.getSuccess(decodeMap(mapText)).pipe( + Option.flatMap((map) => + Option.firstSomeOf([ + Option.liftPredicate(map["debugId"], Predicate.isString), + Option.liftPredicate(map["debug_id"], Predicate.isString), + ]), + ), + Option.map(Str.toLowerCase), + Option.filter((id) => UUID.test(id)), + ) + +/** Whether the map is an index map (`sections`), which the server refuses. */ +export const isIndexMap = (mapText: string): boolean => + Result.match(decodeMap(mapText), { + onFailure: () => false, + onSuccess: (map) => map["sections"] !== undefined, + }) + +/** A version 3 source map as a JSON object; anything else is never rewritten. */ +const decodeV3Map = (mapText: string) => + Option.filter(Result.getSuccess(decodeMap(mapText)), (map) => map["version"] === 3) + +const isJsFile = (file: string): boolean => Arr.some(JS_EXTENSIONS, (ext) => Str.endsWith(ext)(file)) + +const isLocalReference = (url: string): boolean => !/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(url) + +const decodeUrlPath = (url: string): string => + Result.getOrElse( + Result.try(() => decodeURIComponent(url)), + () => url, + ) + +export const fileError = (path: string, verb: string) => (cause: unknown) => + new SourceMapsFileError({ message: `could not ${verb} ${path}`, path, cause }) + +/** Every file below `dir` that passes `keep`, relative to `dir` with `/` separators, sorted. */ +export const listFiles = (dir: string, keep: (file: string) => boolean) => + Effect.gen(function* () { + const fs = yield* FileSystem + const files = yield* fs + .readDirectory(dir, { recursive: true }) + .pipe(Effect.mapError(fileError(dir, "list"))) + return Arr.sort( + Arr.filter( + Arr.map(files, (f) => Str.replaceAll("\\", "/")(f)), + (f) => keep(f) && !Str.includes("/node_modules/")(`/${f}`), + ), + Order.String, + ) + }) + +export interface JsWithMap { + /** Relative to the walked directory, with `/` separators. */ + readonly file: string + readonly jsPath: string + readonly code: string + readonly bytes: Uint8Array + readonly mapPath: Option.Option + /** The map the file names, refused because it lies outside the build directory. */ + readonly refusedMap: Option.Option +} + +/** Whether `target` lies below `root`, both lexically and once symlinks are followed. */ +const isInside = (root: string, target: string) => + Effect.gen(function* () { + const fs = yield* FileSystem + const path = yield* Path + const within = (base: string, file: string) => + Option.isSome(path.resolveWithin(base, path.relative(base, file))) && + path.resolve(base) !== path.resolve(file) + if (!within(root, target)) return false + const real = yield* Effect.all([fs.realPath(root), fs.realPath(target)]).pipe(Effect.option) + return Option.isSome(real) && within(real.value[0], real.value[1]) + }) + +/** + * The JS file's map: the local file its sourceMappingURL names, else `.map`, if it exists. A + * named map outside `root` (a `..` escape, an absolute path, a symlink) is refused, never read. + */ +const resolveMap = (root: string, jsPath: string, code: string) => + Effect.gen(function* () { + const fs = yield* FileSystem + const path = yield* Path + const referenced = Option.filter(sourceMappingUrl(code), ({ url }) => isLocalReference(url)).pipe( + Option.map(({ url }) => + path.resolve(path.dirname(jsPath), decodeUrlPath(Str.replace(/[?#].*$/, "")(url))), + ), + ) + const exists = (candidate: string) => fs.exists(candidate).pipe(Effect.orElseSucceed(() => false)) + if (Option.isSome(referenced) && (yield* exists(referenced.value))) { + return (yield* isInside(root, referenced.value)) + ? { mapPath: referenced, refusedMap: Option.none() } + : { mapPath: Option.none(), refusedMap: referenced } + } + const sibling = `${jsPath}.map` + if (!(yield* exists(sibling))) + return { mapPath: Option.none(), refusedMap: Option.none() } + return (yield* isInside(root, sibling)) + ? { mapPath: Option.some(sibling), refusedMap: Option.none() } + : { mapPath: Option.none(), refusedMap: Option.some(sibling) } + }) + +/** Every `*.js`/`*.mjs`/`*.cjs` file below `dir`, read, with the map it points at (if any). */ +export const findJsFiles = (dir: string) => + Effect.gen(function* () { + const fs = yield* FileSystem + const path = yield* Path + const files = yield* listFiles(dir, isJsFile) + return yield* Effect.forEach(files, (file) => + Effect.gen(function* () { + const jsPath = path.join(dir, file) + const bytes = yield* fs.readFile(jsPath).pipe(Effect.mapError(fileError(jsPath, "read"))) + const code = new TextDecoder().decode(bytes) + const { mapPath, refusedMap } = yield* resolveMap(dir, jsPath, code) + return { file, jsPath, code, bytes, mapPath, refusedMap } satisfies JsWithMap + }), + ) + }) + +/** How many JS files name each map: a map two files share cannot carry either file's id. */ +export const mapUsers = (files: ReadonlyArray): ReadonlyMap => + Arr.reduce( + Arr.getSomes(Arr.map(files, (js) => js.mapPath)), + new Map(), + (users, mapPath) => users.set(mapPath, (users.get(mapPath) ?? 0) + 1), + ) + +// --------------------------------------------------------------------------- +// inject +// --------------------------------------------------------------------------- + +export type InjectStatus = "injected" | "already_injected" | "no_map" | "invalid_map" | "unsafe_map" + +export interface InjectResult { + readonly file: string + readonly status: InjectStatus + readonly debugId: Option.Option + /** True when the map gained `debugId`/`debug_id` (or would, under --dry-run). */ + readonly mapUpdated: boolean + /** The file's map: the one injected, or the one refused or not a version 3 JSON object. */ + readonly mapPath: Option.Option +} + +/** The map carrying `id`, its mappings one line lower when `shift`, marked as moved when `moved`. */ +const taggedMap = ( + map: { readonly [key: string]: unknown }, + id: string, + shift: boolean, + moved: boolean, +): Result.Result => { + const mappings = map["mappings"] + const tagged = { ...map, debugId: id, debug_id: id, ...(moved ? { [SHIFTED_FIELD]: id } : undefined) } + return encodeMap( + shift && Predicate.isString(mappings) ? { ...tagged, mappings: shiftMappings(mappings) } : tagged, + ) +} + +/** Marks a map whose mappings were moved one line down for `id`'s snippet, so they never move twice. */ +const SHIFTED_FIELD = "x_maple_shifted" + +/** Replaces `path` whole: a failed write leaves the old file, never a half-written one. */ +const writeAtomically = (path: string, content: string) => + Effect.gen(function* () { + const fs = yield* FileSystem + const temporary = `${path}.maple-tmp` + yield* fs.writeFileString(temporary, content) + yield* fs.rename(temporary, path) + }).pipe(Effect.mapError(fileError(path, "write"))) + +const injectOne = (js: JsWithMap, shared: boolean, dryRun: boolean) => + Effect.gen(function* () { + const fs = yield* FileSystem + const skip = (status: InjectStatus, mapPath: Option.Option): InjectResult => ({ + file: js.file, + status, + debugId: Option.none(), + mapUpdated: false, + mapPath, + }) + if (Option.isSome(js.refusedMap)) return skip("unsafe_map", js.refusedMap) + if (Option.isNone(js.mapPath)) return skip("no_map", Option.none()) + const mapPath = js.mapPath.value + const mapText = yield* fs.readFileString(mapPath).pipe(Effect.mapError(fileError(mapPath, "read"))) + const map = decodeV3Map(mapText) + if (Option.isNone(map)) return skip("invalid_map", js.mapPath) + + // A map already moved for an id keeps it: its JS write failed after the map was written. + const shiftedFor = Option.filter( + Option.liftPredicate(map.value[SHIFTED_FIELD], Predicate.isString), + (id) => UUID.test(id), + ) + const previous = Option.firstSomeOf([existingDebugId(js.code), shiftedFor]) + const id = Option.getOrElse(previous, () => debugIdFor(js.bytes, mapText)) + // Rollup/Vite `sourcemapDebugIds` write the comment but nothing that reports the id at runtime. + const codeUpdated = !hasRuntimeRegistration(js.code, id) + const mappings = map.value["mappings"] + const movable = !shared && Predicate.isString(mappings) && map.value["sections"] === undefined + const hasId = map.value["debugId"] === id && map.value["debug_id"] === id + // Whether the snippet is (or goes) on the first line: lines below it are one lower. + const prepended = codeUpdated + ? movable && canPrepend(js.code) + : Str.startsWith(`${debugIdSnippet(id)}\n`)(js.code) + // Moved once only: marked by this CLI, or a registered file whose map already carries its id. + const alreadyShifted = Option.contains(shiftedFor, id) || (!codeUpdated && hasId) + const shift = prepended && movable && !alreadyShifted + // A shared map keeps no id: each file sharing it is uploaded with its own. + const mapUpdated = !shared && (shift || !hasId) + if (!dryRun) { + // The map first: a JS file pointing at a map not yet moved would map one line off. + if (mapUpdated) + yield* Effect.fromResult(taggedMap(map.value, id, shift, prepended && movable)).pipe( + Effect.mapError(fileError(mapPath, "encode")), + Effect.flatMap((content) => writeAtomically(mapPath, content)), + ) + if (codeUpdated) + yield* fs + .writeFileString(js.jsPath, injectCode(js.code, id, prepended ? "prepend" : "append")) + .pipe(Effect.mapError(fileError(js.jsPath, "write"))) + } + return { + file: js.file, + status: codeUpdated ? "injected" : "already_injected", + debugId: Option.some(id), + mapUpdated, + mapPath: js.mapPath, + } satisfies InjectResult + }) + +/** Inject debug ids into every JS file below `dir` that has a map. Re-running changes nothing. */ +export const injectDirectory = (dir: string, options: { readonly dryRun: boolean }) => + Effect.flatMap(findJsFiles(dir), (files) => { + const users = mapUsers(files) + return Effect.forEach(files, (js) => + injectOne( + js, + Option.match(js.mapPath, { + onNone: () => false, + onSome: (path) => (users.get(path) ?? 0) > 1, + }), + options.dryRun, + ), + ) + }) diff --git a/packages/sourcemaps/src/limits.ts b/packages/sourcemaps/src/limits.ts new file mode 100644 index 0000000000..74c95cde68 --- /dev/null +++ b/packages/sourcemaps/src/limits.ts @@ -0,0 +1,5 @@ +/** + * Largest source map one upload may carry: also the largest symbolication loads, so an upload that + * succeeds can always be used. Kept apart from the inject code so browser bundles can import it. + */ +export const SOURCE_MAP_MAX_BYTES = 10 * 1024 * 1024 diff --git a/packages/sourcemaps/src/relocate.ts b/packages/sourcemaps/src/relocate.ts new file mode 100644 index 0000000000..0a8a1aeae9 --- /dev/null +++ b/packages/sourcemaps/src/relocate.ts @@ -0,0 +1,125 @@ +// Moves a build's source maps out of its deployed output, so they are never served, and records +// which JS file each belongs to. The Alchemy `Maple.SourceMaps` resource uploads from there. +import { Array as Arr, Effect, Option, Schema, String as Str } from "effect" +import { FileSystem } from "effect/FileSystem" +import { Path } from "effect/Path" +import { fileError, type InjectResult, listFiles } from "./inject.ts" + +/** The manifest written next to relocated maps. */ +export const MANIFEST_FILE = "maple-sourcemaps.json" + +export const SourceMapsManifestEntry = Schema.Struct({ + /** The JS file, relative to the deployed output: the path it is served at. */ + file: Schema.String, + /** The debug id the file registers, when it has one. */ + debugId: Schema.NullOr(Schema.String), + /** The map, relative to the manifest's directory. */ + map: Schema.String, +}) +export type SourceMapsManifestEntry = typeof SourceMapsManifestEntry.Type + +export const SourceMapsManifest = Schema.Struct({ + version: Schema.Literal(1), + files: Schema.Array(SourceMapsManifestEntry), +}) +export type SourceMapsManifest = typeof SourceMapsManifest.Type + +const encodeManifest = Schema.encodeEffect(Schema.fromJsonString(SourceMapsManifest)) +const decodeManifest = Schema.decodeUnknownEffect(Schema.fromJsonString(SourceMapsManifest)) + +/** `mapsDir` is, holds or sits inside a build output: moving maps there could delete the build. */ +export class SourceMapsDirOverlapError extends Schema.TaggedError()( + "@maple/sourcemaps/SourceMapsDirOverlapError", + { message: Schema.String, mapsDir: Schema.String, outDir: Schema.String }, +) {} + +/** One build output and what the inject did to it. */ +export interface BuildOutput { + readonly outDir: string + readonly results: ReadonlyArray +} + +/** + * Moves every `.map` below each output to the same relative path below `mapsDir` and writes one + * {@link MANIFEST_FILE} for all of them. Only the files the previous manifest listed are removed + * first, so anything else in `mapsDir` is left alone; a `mapsDir` that overlaps an output is refused + * before any file is touched. + */ +export const relocateMaps = (mapsDir: string, outputs: ReadonlyArray) => + Effect.gen(function* () { + const fs = yield* FileSystem + const path = yield* Path + const maps = path.resolve(mapsDir) + const within = (base: string, target: string) => { + const relative = path.relative(base, target) + return relative === "" || (!Str.startsWith("..")(relative) && !path.isAbsolute(relative)) + } + const overlapping = Arr.findFirst(outputs, ({ outDir }) => { + const out = path.resolve(outDir) + return within(out, maps) || within(maps, out) + }) + if (Option.isSome(overlapping)) { + return yield* new SourceMapsDirOverlapError({ + message: `The source maps directory ${maps} overlaps the build output ${overlapping.value.outDir}; choose one outside it.`, + mapsDir: maps, + outDir: overlapping.value.outDir, + }) + } + const manifestPath = path.join(maps, MANIFEST_FILE) + // The last build's maps go, by its manifest; nothing it did not write is deleted. + const previous = yield* fs.readFileString(manifestPath).pipe( + Effect.flatMap(decodeManifest), + Effect.map((manifest) => manifest.files), + Effect.orElseSucceed(() => []), + ) + yield* Effect.forEach( + previous, + (entry) => + Option.match(path.resolveWithin(maps, entry.map), { + onNone: () => Effect.void, + onSome: (file) => + fs.remove(file, { force: true }).pipe(Effect.mapError(fileError(file, "remove"))), + }), + { discard: true }, + ) + yield* fs.makeDirectory(maps, { recursive: true }).pipe(Effect.mapError(fileError(maps, "create"))) + const moved = yield* Effect.forEach(outputs, ({ outDir }) => + Effect.gen(function* () { + const files = yield* listFiles(outDir, Str.endsWith(".map")) + // Copy then delete: `mapsDir` may be on another device than the build output. + yield* Effect.forEach( + files, + (file) => + Effect.gen(function* () { + const from = path.join(outDir, file) + const to = path.join(maps, file) + yield* fs.makeDirectory(path.dirname(to), { recursive: true }) + yield* fs.copyFile(from, to) + yield* fs.remove(from) + }).pipe(Effect.mapError(fileError(path.join(outDir, file), "move"))), + { discard: true }, + ) + return files.length + }), + ) + const files = Arr.flatMap(outputs, ({ outDir, results }) => + Arr.flatMap(results, (result) => + result.status === "injected" || result.status === "already_injected" + ? Option.toArray( + Option.map(result.mapPath, (mapPath) => ({ + file: result.file, + debugId: Option.getOrNull(result.debugId), + map: Str.replaceAll("\\", "/")(path.relative(outDir, mapPath)), + })), + ) + : [], + ), + ) + const manifest = yield* encodeManifest({ version: 1, files }).pipe( + Effect.mapError(fileError(MANIFEST_FILE, "encode")), + ) + yield* fs + .writeFileString(manifestPath, manifest) + .pipe(Effect.mapError(fileError(manifestPath, "write"))) + return { moved: Arr.reduce(moved, 0, (sum, n) => sum + n), files } + }) diff --git a/packages/sourcemaps/tsconfig.json b/packages/sourcemaps/tsconfig.json new file mode 100644 index 0000000000..c5f45e7818 --- /dev/null +++ b/packages/sourcemaps/tsconfig.json @@ -0,0 +1,33 @@ +{ + "include": ["**/*.ts", "**/*.tsx"], + "compilerOptions": { + "noUncheckedIndexedAccess": true, + "target": "ES2022", + "module": "ESNext", + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "types": ["node"], + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "verbatimModuleSyntax": true, + "noEmit": true, + "skipLibCheck": true, + "strict": true, + "noFallthroughCasesInSwitch": true, + "noUncheckedSideEffectImports": true, + "plugins": [ + { + "name": "@effect/language-service", + "ignoreEffectWarningsInTscExitCode": false, + "includeSuggestionsInTsc": false, + "diagnosticSeverity": { + // Directives also silence oxlint rules that tsrs never reports, so tsrs flags them all as unused. + "unusedDirective": "off", + "unstableApiUsage": "off", + "schemaNumber": "off", + "schemaClassMissingBrand": "off", + "schemaSync": "off" + } + } + ] + } +} diff --git a/packages/views/src/ui/INDEX.md b/packages/views/src/ui/INDEX.md index 289af604c6..f0eea1608e 100644 --- a/packages/views/src/ui/INDEX.md +++ b/packages/views/src/ui/INDEX.md @@ -169,6 +169,7 @@ existing copies onto it (see `apps/web/CLAUDE.md`). - `packages/views/src/ui/spinner.ts` `spinner`: The loader glyph, spinning, as a status. - `packages/views/src/ui/split-button.ts` `splitButtonClass`: `SplitButton`'s two halves: the classes that join an action button and its chevron menu trigger into one control. - `packages/views/src/ui/sql-editor.ts` `sqlEditor`: `SqlEditor`: a SQL textarea whose text is drawn, syntax-highlighted, by a `
` laid under it.
+- `packages/views/src/ui/stack-frames.ts` `stackFrameRows`, `defaultOpenFrameKey`, `isStackRowOpen`, `stackFrameList`: A symbolicated stack trace as a frame list: library runs fold, in-app frames open on their code.
 - `packages/views/src/ui/stack.ts` `hstackClass`, `vstackClass`, `hstack`, `vstack`: `HStack` and `VStack`: a flex row (items centred by default) or column with its gap on the spacing scale, instead of a hand-written `flex items-center gap-2` string.
 - `packages/views/src/ui/stat-figure.ts` `statFigure`: A headline number with a muted unit.
 - `packages/views/src/ui/status-dot.ts` `statusDot`: A static, decorative status dot.
@@ -236,7 +237,7 @@ existing copies onto it (see `apps/web/CLAUDE.md`).
 - `apps/web/src/page/kit/day-label.ts` `dayKey`, `dayLabel`, `dayEyebrow`: Calendar days in a time zone, for lists grouped by day ("Today", "Yesterday", "Mon 2 Nov").
 - `apps/web/src/page/kit/destination-picker.ts` `destinationPicker`, `pickedDestination`: The alert destinations a form notifies, each removable, then an "Add destination" menu of the rest; the owner keeps the menu's Model and the chosen ids.
 - `apps/web/src/page/kit/detail-header.ts` `detailEyebrow`, `detailTitle`, `detailTitleSkeleton`, `detailActions`: A detail page's title block and its loading skeleton.
-- `apps/web/src/page/kit/disclosure-strip.ts` `disclosureStrip`: A panel's last band that opens on a long block of monospace text.
+- `apps/web/src/page/kit/disclosure-strip.ts` `disclosureStrip`, `monospaceBlock`: A panel's last band that opens on a long block of monospace text.
 - `apps/web/src/page/kit/docs.ts` `docsUrl`: Every docs page the app links to from an empty state, as a path under maple.dev.
 - `apps/web/src/page/kit/environment-switcher.ts` `environmentEntries`, `entryLabel`, `stepEnvironmentSelect`, `environmentSwitcher`: The environment switcher the overview, the service map and a service's page share.
 - `apps/web/src/page/kit/error-chip.ts` `errorChip`: Tool failures read amber: the chip class for a tool error that is not a count.
diff --git a/packages/views/src/ui/stack-frames.ts b/packages/views/src/ui/stack-frames.ts
new file mode 100644
index 0000000000..0bcc380364
--- /dev/null
+++ b/packages/views/src/ui/stack-frames.ts
@@ -0,0 +1,265 @@
+import { cn } from "@maple/ui/lib/utils"
+import type { StackFrame, StackFrameContext } from "@maple/domain/errors/js-stack"
+import { Array as Arr, Option } from "effect"
+import type { Html, HtmlBuilder } from "foldkit/html"
+import { highlightCode } from "../lib/highlight"
+import { icon } from "./icon"
+import { typography } from "./typography"
+
+// A symbolicated stack trace as a frame list: library runs fold, in-app frames open on their code.
+
+/** One row of the list: an app frame, or a run of two or more library frames folded into one. */
+export type StackFrameRow =
+	| Readonly<{ _tag: "Frame"; key: string; frame: StackFrame }>
+	| Readonly<{ _tag: "Library"; key: string; frames: ReadonlyArray }>
+
+type Run = Readonly<{ start: number; inApp: boolean; frames: ReadonlyArray }>
+
+/** The frames as rows, top of stack first: consecutive library frames fold into one row. */
+export const stackFrameRows = (frames: ReadonlyArray): ReadonlyArray => {
+	const none: ReadonlyArray = []
+	const runs = Arr.reduce(frames, none, (acc, frame, index) =>
+		Option.match(Arr.last(acc), {
+			onSome: (run) =>
+				run.inApp === frame.in_app
+					? [...Arr.dropRight(acc, 1), { ...run, frames: [...run.frames, frame] }]
+					: [...acc, { start: index, inApp: frame.in_app, frames: [frame] }],
+			onNone: () => [{ start: index, inApp: frame.in_app, frames: [frame] }],
+		}),
+	)
+	return Arr.flatMap(runs, (run): ReadonlyArray =>
+		!run.inApp && run.frames.length > 1
+			? [{ _tag: "Library", key: `lib-${run.start}`, frames: run.frames }]
+			: Arr.map(run.frames, (frame, offset) => ({
+					_tag: "Frame",
+					key: `frame-${run.start + offset}`,
+					frame,
+				})),
+	)
+}
+
+/** The row open on load: the top in-app frame, when it carries code context. */
+export const defaultOpenFrameKey = (frames: ReadonlyArray): string | null =>
+	Option.match(
+		Arr.findFirstIndex(frames, (frame) => frame.in_app),
+		{
+			onNone: () => null,
+			onSome: (index) => (frames[index]?.context === null ? null : `frame-${index}`),
+		},
+	)
+
+/** Whether a row is open: its default, flipped when its key is in `toggled`. */
+export const isStackRowOpen = (
+	frames: ReadonlyArray,
+	toggled: ReadonlyArray,
+	key: string,
+): boolean => (defaultOpenFrameKey(frames) === key) !== toggled.includes(key)
+
+export type StackFrameListOptions = Readonly<{
+	/** Top of stack first, as the backend symbolicated them. */
+	frames: ReadonlyArray
+	/** Row keys flipped from their default (the top in-app frame open, the rest closed). */
+	toggled: ReadonlyArray
+	onToggle: (key: string) => M
+	/** Prefixes the panel ids, unique on the page. */
+	idPrefix: string
+	className?: string
+}>
+
+const ROW_CLASS = "w-full min-w-0 px-4 py-1.5 text-left"
+const TOGGLE_CLASS = cn(
+	ROW_CLASS,
+	"cursor-pointer outline-none hover:bg-surface-sunken active:bg-surface-sunken focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-inset",
+)
+
+const chevron = (h: HtmlBuilder, isOpen: boolean): Html =>
+	icon(h, isOpen ? "ChevronDownIcon" : "ChevronRightIcon", { size: 12, className: "shrink-0" })
+
+const chevronSpacer = (h: HtmlBuilder): Html => h.span([h.Class("size-3 shrink-0")], [])
+
+const position = (frame: StackFrame): string =>
+	frame.line === null ? "" : frame.column === null ? `:${frame.line}` : `:${frame.line}:${frame.column}`
+
+/** The frame's function, then where it is: the original source path once a map resolved it. */
+const frameLabel = (h: HtmlBuilder, frame: StackFrame): ReadonlyArray => [
+	typography(
+		h,
+		{
+			size: "xs",
+			mono: true,
+			tone: frame.in_app ? "foreground" : "subtle",
+			weight: frame.in_app ? "medium" : "normal",
+			className: "min-w-0 break-all",
+		},
+		[frame.function ?? "(anonymous)"],
+	),
+	typography(
+		h,
+		{ size: "xs", mono: true, tone: frame.in_app ? "muted" : "subtle", className: "min-w-0 break-all" },
+		[frame.file ?? "unknown location", position(frame)],
+	),
+]
+
+const labelLine = (h: HtmlBuilder, lead: Html, label: ReadonlyArray): Html =>
+	h.span(
+		[h.Class("flex min-w-0 items-baseline gap-2")],
+		[lead, h.span([h.Class("flex min-w-0 flex-wrap items-baseline gap-x-2")], label)],
+	)
+
+const codeLine = (
+	h: HtmlBuilder,
+	number: number | null,
+	text: string,
+	isError: boolean,
+	key: string,
+	lang: string,
+): Html =>
+	h.div(
+		[
+			h.Key(key),
+			h.Class(cn("flex", isError && "bg-severity-error-a2")),
+			...(isError ? [h.DataAttribute("error-line", "")] : []),
+		],
+		[
+			h.span(
+				[
+					h.Class(
+						cn(
+							"w-12 shrink-0 pr-3 text-right tabular-nums select-none",
+							isError ? "text-severity-error" : "text-foreground-subtle",
+						),
+					),
+					h.AriaHidden(true),
+				],
+				[number === null ? "" : String(number)],
+			),
+			// Highlighted line by line: each row keeps its own number and error tint.
+			h.span(
+				[
+					h.Class("pr-4 whitespace-pre text-foreground"),
+					h.InnerHTML(text === "" ? " " : highlightCode(text, lang)),
+				],
+				[],
+			),
+		],
+	)
+
+/** The frame's source around the error line, numbered, the error line marked. */
+const codeContext = (
+	h: HtmlBuilder,
+	frame: StackFrame,
+	context: StackFrameContext,
+	id: string,
+): Html => {
+	const first = frame.line === null ? null : frame.line - context.pre.length
+	const numberAt = (offset: number) => (first === null ? null : first + offset)
+	const lang = frame.file ?? ""
+	return h.div(
+		[
+			h.Id(id),
+			h.Class(
+				"overflow-x-auto border-y border-border-subtle bg-surface-sunken py-1.5 font-mono text-xs leading-5",
+			),
+		],
+		[
+			h.div(
+				[h.Class("w-max min-w-full")],
+				[
+					...Arr.map(context.pre, (text, i) =>
+						codeLine(h, numberAt(i), text, false, `pre-${i}`, lang),
+					),
+					codeLine(h, numberAt(context.pre.length), context.line, true, "line", lang),
+					...Arr.map(context.post, (text, i) =>
+						codeLine(h, numberAt(context.pre.length + 1 + i), text, false, `post-${i}`, lang),
+					),
+				],
+			),
+		],
+	)
+}
+
+const frameRow = (
+	h: HtmlBuilder,
+	options: StackFrameListOptions,
+	frame: StackFrame,
+	key: string,
+): Html => {
+	const id = `${options.idPrefix}-${key}`
+	const context = frame.context
+	if (context === null || !frame.in_app)
+		return h.li([h.Key(key), h.Class(ROW_CLASS)], [labelLine(h, chevronSpacer(h), frameLabel(h, frame))])
+	const isOpen = isStackRowOpen(options.frames, options.toggled, key)
+	return h.li(
+		[h.Key(key)],
+		[
+			h.button(
+				[
+					h.Type("button"),
+					h.Class(TOGGLE_CLASS),
+					h.AriaExpanded(isOpen),
+					...(isOpen ? [h.AriaControls(id)] : []),
+					h.OnClick(options.onToggle(key)),
+				],
+				[labelLine(h, chevron(h, isOpen), frameLabel(h, frame))],
+			),
+			...(isOpen ? [codeContext(h, frame, context, id)] : []),
+		],
+	)
+}
+
+const libraryRow = (
+	h: HtmlBuilder,
+	options: StackFrameListOptions,
+	frames: ReadonlyArray,
+	key: string,
+): Html => {
+	const id = `${options.idPrefix}-${key}`
+	const isOpen = isStackRowOpen(options.frames, options.toggled, key)
+	return h.li(
+		[h.Key(key)],
+		[
+			h.button(
+				[
+					h.Type("button"),
+					h.Class(TOGGLE_CLASS),
+					h.AriaExpanded(isOpen),
+					...(isOpen ? [h.AriaControls(id)] : []),
+					h.OnClick(options.onToggle(key)),
+				],
+				[
+					labelLine(h, chevron(h, isOpen), [
+						typography(h, { size: "xs", tone: "muted" }, [`${frames.length} library frames`]),
+					]),
+				],
+			),
+			...(isOpen
+				? [
+						h.ol(
+							[h.Id(id), h.Class("pl-5")],
+							Arr.map(frames, (frame, i) =>
+								h.li(
+									[h.Key(`${key}-${i}`), h.Class(ROW_CLASS)],
+									[labelLine(h, chevronSpacer(h), frameLabel(h, frame))],
+								),
+							),
+						),
+					]
+				: []),
+		],
+	)
+}
+
+/**
+ * `StackFrameList`: a symbolicated stack trace, top of stack first. Library frames are muted and
+ * consecutive ones fold into one "N library frames" row; in-app frames with source open on their
+ * code context, the top one open by default. The owner's Model holds the flipped row keys.
+ */
+export const stackFrameList = (h: HtmlBuilder, options: StackFrameListOptions): Html =>
+	h.ol(
+		[h.Class(cn("min-w-0 py-1", options.className)), h.DataAttribute("slot", "stack-frames")],
+		Arr.map(stackFrameRows(options.frames), (row) =>
+			row._tag === "Frame"
+				? frameRow(h, options, row.frame, row.key)
+				: libraryRow(h, options, row.frames, row.key),
+		),
+	)
diff --git a/test/alchemy/secret-grants.test.ts b/test/alchemy/secret-grants.test.ts
index 9cd64623dd..a84fbfc47a 100644
--- a/test/alchemy/secret-grants.test.ts
+++ b/test/alchemy/secret-grants.test.ts
@@ -10,6 +10,7 @@ import { managedDbSecrets, type MapleStage, workersObservabilitySecrets } from "
 import { selfObservabilityEnv } from "@maple/infra/env"
 import type { SecretConsumer } from "@maple/infra/secret"
 import { resolveAs, resolveDerived } from "@maple/infra/secret-guard"
+import { webSourceMapsApiKey } from "@maple/infra/self-source-maps"
 import * as Catalog from "@maple/infra/secrets"
 import { aiConfiguredEnv } from "../../apps/ai/src/resources/env.ts"
 import { alertingConfiguredEnv } from "../../apps/alerting/src/resources/env.ts"
@@ -99,7 +100,8 @@ const DEPLOYABLES = {
 	sandbox: [sandboxSecrets],
 	status: onEveryStage((stage) => selfObservabilityEnv(stage, "us")),
 	"audit-archive": onEveryStage((stage) => selfObservabilityEnv(stage, "us")),
-	web: onEveryStage((stage) => selfObservabilityEnv(stage, "us")),
+	// Its Worker env, and the deploy's source map upload key (`@maple/infra/self-source-maps`).
+	web: [...onEveryStage((stage) => selfObservabilityEnv(stage, "us")), webSourceMapsApiKey],
 	landing: [landingBuildSecrets],
 	ingest: [ingestSecrets],
 	scraper: [scraperSecrets],
diff --git a/tsconfig.alchemy-maple.json b/tsconfig.alchemy-maple.json
index 741175aca5..b674d65250 100644
--- a/tsconfig.alchemy-maple.json
+++ b/tsconfig.alchemy-maple.json
@@ -10,7 +10,9 @@
 			"@maple/widgets": ["./packages/widgets/src/index.ts"],
 			"@maple/widgets/*": ["./packages/widgets/src/*"],
 			"@maple/query-model": ["./packages/query-model/src/index.ts"],
-			"@maple/primitives": ["./packages/primitives/src/index.ts"]
+			"@maple/primitives": ["./packages/primitives/src/index.ts"],
+			"@maple/sourcemaps": ["./packages/sourcemaps/src/index.ts"],
+			"@maple/sourcemaps/*": ["./packages/sourcemaps/src/*"]
 		}
 	}
 }