# SpanSlice > SpanSlice runs rules inside your services that decide which OpenTelemetry spans reach your observability backend, and in what shape. Its API and MCP server let scripts and agents read and change those rules. # Install the Node SDK Source: https://docs.spanslice.com/start/install/ The `spanslice` package sets up OpenTelemetry for Node. It fetches the rules your project defines in SpanSlice, applies them to every span in your process, and picks up changes without a restart. ## Install ```sh npm install spanslice ``` ## Get an API key Each runtime environment (production, staging, …) has its own API keys. Create them under your project's **Settings › API keys** in the app. SpanSlice shows a key once, when you create it, and keeps only its hash. Set the key as `SPANSLICE_API_KEY` wherever that environment runs. Without a key, the SDK stays off. To replace a key, create a new one, deploy it, and then revoke the old one. ## Initialize before your app loads Create a file that starts the SDK, and load it with `--import`. Instrumentations can then patch libraries before your code imports them: ```ts // src/instrument.ts import { spanSliceInit } from 'spanslice' import { HttpInstrumentation } from '@opentelemetry/instrumentation-http' const telemetry = spanSliceInit({ service: 'api', // the service in SpanSlice; also service.name instrumentations: [new HttpInstrumentation()], }) await telemetry.ready ``` ```sh node --import ./src/instrument.ts server.js ``` `service` must name a service deployed to the API key's environment. Otherwise, the SDK stays off. `ready` resolves when the first config applies. If the API can't be reached, it resolves after `readyTimeoutMs` (5 seconds by default) instead. Until the first config arrives, the SDK holds spans. It doesn't send them unfiltered. ## Main options | Option / env | Default | Meaning | | -------------------------------------------- | --------------------------- | ------------------------------------------------------------------------------------------- | | `apiKey` / `SPANSLICE_API_KEY` | — | The environment's `ss_…` key. | | `service` | `OTEL_SERVICE_NAME` | The service's slug or name in SpanSlice. | | `exporter` / `SPANSLICE_EXPORTER` | `remote` | `remote` (where the project sends data), `otlp` (your own collector), `console`, or `none`. | | `readyTimeoutMs` | `5000` | How long `ready` waits for the first config. | | `apiUrl` / `SPANSLICE_API_URL` | `https://api.spanslice.com` | Where the SDK fetches its config. | | `deployedSha` / `SPANSLICE_DEPLOYED_SHA` | your host's commit variable | The commit this process runs, shown per process in Live Tail. | | `repositoryUrl` / `SPANSLICE_REPOSITORY_URL` | — | The repository `deployedSha` is in, so Live Tail links to the commit. | On Render, Vercel, Railway and Heroku, `deployedSha` defaults to the commit the platform sets (`RENDER_GIT_COMMIT`, `VERCEL_GIT_COMMIT_SHA`, `RAILWAY_GIT_COMMIT_SHA`, `HEROKU_BUILD_COMMIT`). You only need to set `repositoryUrl`, or set the service's Repository on its page instead. The SDK puts both values on the resource as `vcs.ref.head.revision` and `vcs.repository.url.full`, so your spans and metrics carry the release too. With the default `remote` exporter, SpanSlice tells the SDK where to send data, such as your Honeycomb environment. Your code names no vendor. Spans go straight from your process to that backend. They don't pass through SpanSlice. ## Export batching Spans are sent in batches. To change how, pass `batch`: ```ts spanSliceInit({ service: 'api', batch: { scheduledDelayMillis: 500, maxQueueSize: 40_000 }, }) ``` | Setting | Default | Env | | ---------------------- | ------- | -------------------------------- | | `scheduledDelayMillis` | `2000` | `OTEL_BSP_SCHEDULE_DELAY` | | `exportTimeoutMillis` | `10000` | `OTEL_BSP_EXPORT_TIMEOUT` | | `maxQueueSize` | `20000` | `OTEL_BSP_MAX_QUEUE_SIZE` | | `maxExportBatchSize` | `2048` | `OTEL_BSP_MAX_EXPORT_BATCH_SIZE` | A setting passed in `batch` wins over its variable. The queue holds four whole traces, because a kept trace is sent all at once. Spans that arrive while it's full are dropped and counted as `queue_full`. ## Your own span processors To run a span processor of your own, pass `spanProcessors`. It's given the processor that exports and returns the processors kept spans go to: ```ts spanSliceInit({ service: 'api', spanProcessors: (exporting) => [new EnhancedSpanProcessor(exporting)], }) ``` Their `onStart` and `onEnding` run for every span before your rules do, so rules can match attributes they set. `onEnd` gets only the spans your rules keep. While the SDK is off, `spanProcessors` isn't called. ## Scheduled work Cron jobs, `setInterval` loops and scripts aren't started by a request, so nothing opens a trace for them. `newTrace(name, fn, options?)` wraps `fn` so that each call runs in a span named `name` and starts a new trace: ```ts import { CronJob } from 'cron' import { newTrace } from 'spanslice' new CronJob( '*/2 * * * *', newTrace('cron.cleanup', async () => { await deleteExpiredSessions() }), null, true, ) ``` The span is always a root, even if another span is active when the job runs. A timer keeps the context it was scheduled in. If you create the job inside a span, a plain span around each tick would make every tick a child of that one, and all ticks would share its trace. The span is active while `fn` runs, so spans started inside it are its children. It ends when `fn` returns or its promise settles. If `fn` throws or rejects, the span records the error with status ERROR, and the error continues to your code. `this` and the arguments reach `fn` unchanged. `options.attributes` and `options.kind` set the span's attributes and kind. Give each job one fixed name, such as `cron.cleanup`. Don't put a date or an id in it: rules match on the name. Spans from `newTrace` have the instrumentation scope `spanslice`. While the SDK is off, `fn` runs as written. ## Logging The SDK prints only when it can't do its job: a service it can't find, a rejected API key, another tracer provider registered first, an environment with nowhere to export. Everything else is logged with [debug](https://www.npmjs.com/package/debug), under one namespace per area: ```sh DEBUG=spanslice:* node --import ./src/instrument.ts server.js ``` | Namespace | Logs | | ---------------------------- | ----------------------------------------------------------- | | `spanslice:sdk` | Startup, shutdown, and errors thrown while deciding spans | | `spanslice:config` | Each config applied, and failed fetches | | `spanslice:rules` | Rules skipped because they don't compile | | `spanslice:live` | The live connection | | `spanslice:tail` | Live Tail sessions | | `spanslice:archive` | The span archive and its uploads | | `spanslice:alerts` | Alerts that couldn't be sent | | `spanslice:instrumentations` | Instrumentations switched on, off or reconfigured | | `spanslice:metrics` | Span metrics and metrics settings | | `spanslice:spans` | One line per kept and dropped span, with the rules involved | `debug: true` (or `SPANSLICE_DEBUG=1`) turns on all of them. To send everything to your own logger instead, pass `logger: { error, warn, info }`. Without `error`, those messages go to `warn`. Next: [write your first rule](/start/first-rule/). # Keep your NodeSDK setup Source: https://docs.spanslice.com/start/node-sdk/ If your service already starts OpenTelemetry with `NodeSDK` from `@opentelemetry/sdk-node`, you can keep that setup and its exporters. `spanslice/sdk-node` wraps your `NodeSDK` class, so the options you pass today still work: ```ts // before import { NodeSDK } from '@opentelemetry/sdk-node' const sdk = new NodeSDK({ ...options }) sdk.start() ``` ```ts // after import { NodeSDK } from '@opentelemetry/sdk-node' import { makeSpanSliceSDK } from 'spanslice/sdk-node' const SpanSliceSDK = makeSpanSliceSDK(NodeSDK, { service: 'api' }) const sdk = new SpanSliceSDK({ ...options }) sdk.start() ``` Set `SPANSLICE_API_KEY` as described in [Install the Node SDK](/start/install/#get-an-api-key). The second argument takes the same options as `spanSliceInit`. The exceptions are `exporter`, `spanProcessors`, `batch`, `instrumentations` and `resourceAttributes`, which come from your `NodeSDK` options. ## What changes - Every span goes through your rules before it reaches the exporters you configured (`traceExporter`, `spanProcessors`, or the `OTEL_TRACES_EXPORTER` variables). Spans a rule drops never reach them. - SpanSlice can switch your instrumentations off, and change their options, from **Traces › Instrumentation**. No restart is needed. - Until the first config arrives, spans are held. If it doesn't arrive within `readyTimeoutMs` (5 seconds by default), the SDK sends spans unfiltered instead of holding them. `await sdk.ready` waits for the config. Everything else stays with `NodeSDK`: the sampler, propagators, metrics, logs and resource detection. ## When SpanSlice stays out of the way Without `SPANSLICE_API_KEY` or a service name, or with `OTEL_SDK_DISABLED=true`, `SpanSliceSDK` behaves exactly like `NodeSDK`. It does the same when the exporter is set only through environment variables that the SDK can't rebuild: `otlp` over `grpc` or `http/json`, or `zipkin`. For those, pass the exporter as `traceExporter` instead, and SpanSlice sits in front of it. SpanSlice takes the service name from the first of these that's set: the `service` option, `NodeSDK`'s `serviceName`, the `service.name` on your resource, or `OTEL_SERVICE_NAME`. # Write your first rule Source: https://docs.spanslice.com/start/first-rule/ Rules live under **Traces › Rules** in the app. A rule reads as a sentence: > When **a root span** is **completed** and matches **Span Attribute `http.route` is `/healthz`**, then > **Drop Trace**. Each part is a choice in the editor: - **Which spans** the rule looks at: any span, a root span, or a child span. - **When** it runs: as the span is **created**, or once it has **completed**. A completed span knows more, such as its duration, its end attributes, and whether it errored. `http.route` is set only when an HTTP span ends, so this rule runs at completion. - **Conditions** the span must match. A rule with no conditions matches every span it looks at. - **Actions** to take on a match, run in order. ## Try it before saving **Traces › Rules › Test** runs your rules against example spans, or against spans from your archive. It uses the same engine as the SDK. It steps through each rule and shows which conditions matched and what each action did. ## Save and roll out Saved rules reach running services within seconds, over the SDK's live connection. No restart is needed. A change applies to traces that start after it arrives. Traces already in flight finish under the rules they started with. Next, read [how rules run](/concepts/rules/). It covers the details that matter once you have more than one rule. # How rules run Source: https://docs.spanslice.com/concepts/rules/ A rule has four parts. Its **target** is the set of spans it looks at. Its **stage** is when it runs. Its **conditions** are what a span must match, and its **actions** are what to do with a match. In the editor, a rule reads as a sentence: "When [any span] is [completed] and matches…, then…". ## Targets | Target | Looks at | | ------------ | ------------------------------------------------------------------------------------------------------------------------ | | any span | every span | | a root span | spans with no parent in this process: a trace's true root, or the entry span of a request that came from another service | | a child span | spans whose parent is in this process | "Root" always means root within one process. When service A calls service B, B's server span counts as a root for B's rules. ## Stages | Stage | Runs | Can see | | --------- | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | | created | when the span starts | its name, kind, start attributes, service and library, whether it's a root, the current time | | completed | when the span ends, and again when its trace's root ends | everything above, plus end attributes, Span Duration and Has Error. Trace conditions run only in the root-end pass. | Use **completed** for anything you only know at the end. For example, HTTP instrumentation sets `http.route` and renames its span only as the span ends. The trace conditions (**Trace Duration**, **Trace Span Count** and **Spans In Trace**) describe the whole trace. SpanSlice can check them only once the root ends, so the editor offers them only on completed rules. ## Conditions Conditions sit in groups. Each group joins its conditions with **and** or **or**, and groups can nest. A rule with no conditions matches every span its target covers. | Condition | Operators | | ------------------------------------- | ----------------------------------------------------------------------------------------------- | | Service Name, Span Name, Library Name | is, is not, in, not in, contains, does not contain, starts with, matches regex | | Span Attribute | the text operators, plus exists, does not exist, =, >, >=, <, <=, between | | Resource Attribute | as Span Attribute, on the resource of the process that made the span | | Span Attribute Key | is, contains, starts with, matches regex, against every attribute key of the span and its trace | | Span Kind | is, is not, in, not in: Internal, Server, Client, Producer or Consumer | | Span Duration, Trace Duration | =, >, >=, <, <=, between | | Has Error | is true, is false | | Trace Span Count | =, >, >=, <, <= | | Spans In Trace | any, at least n, at most n, none, all, of the spans matching a nested condition | | Current Time | between two times of day, in the process's local time zone | **in** and **not in** take a list of exact values. To fill the list, paste a column or a comma-separated list. Like the other negative operators, **not in** also matches a span that doesn't have the value at all. **matches regex** uses RE2 syntax. The pattern matches anywhere in the value unless you anchor it with `^` or `$`, and `(?i)` makes it case-insensitive. RE2 matches in time linear in the length of the value, so no pattern can stall your service on a crafted request. The trade-off is that RE2 has no lookahead, lookbehind or backreferences. SpanSlice rejects a pattern that uses them when you save the rule. **Library Name** is the span's instrumentation scope, such as `@opentelemetry/instrumentation-knex`. **Span Attribute** reads the span's own attribute first, then the trace's attributes. Trace attributes come from [Set Trace Attribute](/concepts/actions/#set-trace-attribute) and from `setTraceAttributes` in your code. The rule sees the value the span would leave with. SpanSlice counts a trace attribute from the moment it's set. A span that started before the attribute was set doesn't see it in its created rules, but its completed rules do. **Span Attribute Key** with `is` looks up one key, which costs the same as a Span Attribute `exists`. With contains, starts with or matches regex, it checks every attribute key on every span it reaches, which makes it the most expensive condition. SpanSlice evaluates those after the other conditions in its group. To limit the spans they run on, narrow the rule by span name or library first. ## Rule order Rules run in order: the service's own rules first, then the project's. Every matching rule runs its actions. A later rule can override what an earlier one set. See [sampling](/concepts/sampling/) for how sample rates combine. **Stop Rule Evaluation** ends rule processing for that span at that stage. ## Spans are held until the trace is decided The SDK holds every span in a trace until the trace's local root ends. That lets a completed rule on the root see the whole trace, and lets sampling keep or drop the trace as one unit. To bound memory, the SDK sends a trace early when it reaches 5,000 spans, when it's 120 seconds old, or when more than 1,000 traces are open. An early-sent trace skips the root-end pass and uses the rate its created rules set. Spans that end after their trace was sent follow the trace's decision for 30 seconds. ## Seeing which rule did what The SDK stamps each span with the rules it applied: | Attribute | Meaning | | ---------------------------------------------------- | ------------------------------------------------------------------------------------------ | | `spanslice.rules` / `spanslice.rule_names` | every rule that matched the span | | `spanslice.dropped_by` / `spanslice.dropped_by_name` | the rule whose Drop Span or Collapse Span removed it | | `spanslice.sampled_by` / `spanslice.sampled_by_name` | the rule that set the trace's sample rate or dropped the trace, on every span of the trace | A rule's name is optional. An unnamed rule uses a title generated from what it does, such as `Drop traces with http.route = /healthz`. The title shows in the app and in the `*_name` attributes, and it changes as you edit the rule. If a query or board depends on a rule's name, give the rule a name. # Actions Source: https://docs.spanslice.com/concepts/actions/ Actions run in order when a rule matches. **Trace** actions act on the whole trace, and you can use them only on the rule itself, not inside For Descendant Spans. **Span** actions act on the matched span, and you can also use them inside [For Descendant Spans](#for-descendant-spans). Most actions can appear only once in a rule's action list. Attribute-setting and redaction actions can repeat. ## Set Span Attribute **Span.** Sets an attribute on the span. The value can be a template that reads the span's other attributes, such as `{http.method} {http.route}`. It's set on the live span while the span is open, or on the span as sent if it has already ended. ## Set Trace Attribute **Trace.** Sets an attribute on every span in the trace, both spans that have already ended and spans that end later. If a span has its own value for the same key, that value wins. The value can be a template, read from the span that matched the rule. Rules that run later can match the attribute with a **Span Attribute** condition. An attribute set during the root-end pass isn't seen by the other rules in that pass. ## Set Root Span Attribute **Trace.** Sets an attribute on the trace's local root span, replacing any existing value. The value can be a template, read from the span that matched the rule. ## Redact Span Attribute **Span.** Replaces an attribute's value before the value leaves the process: - **Replace with text**: a fixed string, `[Redacted]` by default. - **Mask**: keeps the first and last characters, like `p****d`. - **Type and length**: like `String<8>`. The original value is never exported or archived, even if the attribute is set again later. Templates that read it, in Rename Span or a Set … Attribute action, get the redacted value too, whichever rule or stage runs first. The one exception: a trace or root attribute copied onto spans that were already sent before the redaction matched. Redact in the **created** stage to rule that out. ## Drop Span **Span.** Removes the span. With **Reparent children** (the default), its children move up to the nearest kept ancestor, so the trace stays connected. With **Drop children**, they're dropped too. With **Drop children**: ## Drop Trace **Trace.** Drops every span in the trace. It overrides every sample rate. See [Sampling](/concepts/sampling/#drop-trace-and-drop-traces-without-errors). ## Drop Traces Without Errors **Trace.** Drops the trace unless a span in it has an error. ## Set Sample Rate **Trace.** Keeps 1 in N traces, decided by trace ID, and sets `SampleRate` on the spans it sends. Its mode decides whether it replaces a rate an earlier rule set. **If Not Set** applies only when no earlier rule set a rate. **Overriding Any Existing Sampling** replaces the earlier rate. See [Sampling](/concepts/sampling/). ## Set Span Sample Rate **Span.** Keeps 1 in N of the matched spans inside a kept trace, decided by span ID. A span that isn't kept is dropped, and its children move up. A kept span carries `SampleRate` = trace rate × span rate. It has the same modes as Set Sample Rate. See [Sampling](/concepts/sampling/#set-span-sample-rate-keep-1-in-n-of-a-span). ## Rename Span **Span.** Changes the span's name. Like attribute values, the name can be a template, such as `{http.method} {http.route}`. ## Drop Attributes **Span.** Removes the attributes you list, by exact key. Enter keys one at a time, or paste a list separated by commas or new lines. It applies like Drop Matched Attributes, below: when the span is sent, so keys set after the rule ran are dropped too. ## Drop Matched Attributes **Span.** Removes every attribute whose key matches one of this rule's **Span Attribute Key** conditions, so the rule needs at least one. SpanSlice applies it as the span is sent, after redactions. Keys set after the rule ran are caught too. SpanSlice never touches its own `spanslice.*` attributes or `SampleRate`. ## Prefix Matched Attributes **Span.** Moves every attribute whose key matches one of the rule's **Span Attribute Key** conditions under a prefix, such as `legacy.`. It applies like Drop Matched Attributes. If one rule drops a key and another prefixes it, the key is dropped. ## Collapse Span **Span.** Removes the span, copies its attributes onto its children, and moves the children up to its parent. Use it for wrapper spans whose only value is an attribute or two. - **Attributes**: all of them, all except a list, or only a list. - **Conflicts**, when a child already has the key: **Keep child attribute** leaves the child's value; **Keep parent attribute** and **Ignore conflicts** write the collapsed span's value over it. When several ancestors collapse, the outermost applies first. ## For Descendant Spans **Span.** Runs nested actions on the matched span's descendants. You can give the nested actions their own conditions, so they run only on descendants that match. Only span actions go inside it. A **For Descendant Spans** action can't contain another one. ## Roll Up Spans **Span.** Replaces a run of like spans with one summary span when the trace is sent. For example, a loop of a thousand Redis calls leaves as one span. SpanSlice groups spans by parent, name, and the values of the **group by** attributes. A group needs at least the **minimum** count, which is 2 by default. The summary span runs from the first member's start to the last member's end. It keeps the attributes that every member shares, and it has ERROR status if any member did. It carries: - `spanslice.rollup.count` and `spanslice.rollup.error_count` - `spanslice.rollup.duration_ms.sum`, `.min`, `.max` and `.avg`, rounded to hundredths of a millisecond The members' children move under the summary. The summary keeps the members' name unless **rename** is on, which names it `{name} (rollup)`, so `HSCAN` becomes `HSCAN (rollup)`. Grouping still uses the members' own name. ## Stop Rule Evaluation **Span.** No later rule runs for this span at this stage. # Sampling Source: https://docs.spanslice.com/concepts/sampling/ SpanSlice has two sampling actions, and they work at different levels: - **Set Sample Rate** decides whether the whole **trace** is kept. - **Set Span Sample Rate** thins out individual **spans** inside a trace that was kept. | | Set Sample Rate | Set Span Sample Rate | | --------------------------- | -------------------------------------------------------------- | ----------------------------------------------------------- | | Decides | whether the trace is kept | whether this span is kept, inside a kept trace | | Kept 1 in N by | trace ID, so every span of a trace agrees | span ID, so each span is decided on its own | | What a "no" removes | the whole trace | the span; its children move up to the nearest kept ancestor | | `SampleRate` on what's sent | the trace rate | trace rate × span rate | | Inside For Descendant Spans | no | yes | | When it's decided | in rule order: created rules on the root, then completed rules | when the trace is sent | ## Set Sample Rate: keep 1 in N traces "Keep 1 in 10 traces" keeps a tenth of the traces the rule matches and drops the rest, along with all their spans. Every span in a kept trace carries `SampleRate = 10`. Honeycomb reads that attribute and counts each event as ten, so counts, sums and rates in your queries still reflect real traffic. SpanSlice makes the keep-or-drop decision from the trace ID. Every service that uses the same rate makes the same decision for a given trace, so a sampled trace has no gaps where one service kept its part and another didn't. ## Set Span Sample Rate: keep 1 in N of a span Some traces are worth keeping, but they contain hundreds of near-identical spans: a Redis `HSCAN` loop, a batch of inserts, a polling call. **Set Span Sample Rate** keeps 1 in N of those spans and leaves the rest of the trace alone. - A span that isn't kept is dropped. Its children move up to its nearest kept ancestor, so the trace stays connected. - A kept span carries `SampleRate` = trace rate × span rate. In a trace kept 1 in 10, a span kept 1 in 5 carries `SampleRate = 50`, because it stands for fifty such spans. - SpanSlice decides it when the trace is sent. A span still open at that point keeps the rate it had. Because it works span by span, you can put it inside **For Descendant Spans**. For example, on root spans: > When **a root span** is **completed** and matches **Span Name is `GET /reports`**, then **For Descendant > Spans** matching **Span Name starts with `HSCAN`**: **Set Span Sample Rate** 1 in 20. To thin out a span wherever it appears, use the action directly in a rule that targets any span: > When **any span** is **completed** and matches **Span Name starts with `HSCAN`**, then **Set Span Sample > Rate** 1 in 20. To remove the matching spans instead, use **Drop Span**. To summarize them, use **Roll Up Spans**, which replaces a run of like spans with one span that carries their count and timings. ## When more than one rule sets a rate Several rules can match the same trace. Both actions have a mode that says what happens when a rate is already set: - **If Not Set** (the default) applies only if no earlier rule set a rate. - **Overriding Any Existing Sampling** replaces whatever an earlier rule set. Here, "earlier" means this order: created rules on the trace's root first, then completed rules, span by span in the order the spans started. Within a stage, rules run in [rule order](/concepts/rules/#rule-order). With the default mode, the first rate set wins. A broad rule, such as "keep 1 in 10 traces", placed after specific rules acts as a fallback. If a specific rule must win regardless, such as "keep every trace from the billing service", set it to override. ## Drop Trace and Drop Traces Without Errors - **Drop Trace** drops the whole trace and beats every rate, including overriding ones. A Drop Trace from a created rule is final. - **Drop Traces Without Errors** drops the trace unless a span in it has an error. ## Traces sent early A trace is sent early when it grows past the span or age limit, when more than 1,000 traces are open, or when the process shuts down. An early-sent trace skips the completed rules on its root, and it's kept at the rate its created rules set. See [spans are held until the trace is decided](/concepts/rules/#spans-are-held-until-the-trace-is-decided). # Synchronous spans Source: https://docs.spanslice.com/concepts/sync-spans/ Auto-instrumentation wraps every middleware function and many library calls in a span. Many of these spans start and end without waiting on anything, such as a CORS check, middleware that calls the next function directly, or a template helper. They add rows to every trace but say little about where the time went. **Synchronous Span Handling** drops them as they end, unless a **keep rule** matches. ## What counts as synchronous A span is synchronous when it starts and ends with no `await` in between, so both happen in the same microtask. An `await` makes a span asynchronous, even if the awaited call resolves without doing any I/O. ## Dropped as it ends SpanSlice decides a synchronous span as soon as it ends, not when its trace ends: - Its children move up to its parent, so the trace stays connected. Spans that start under it later attach to its nearest kept ancestor as well. - It leaves memory right away. It still counts toward **Trace Span Count**. - A span that a rule already removed with **Drop Span** or **Collapse Span** stays removed. A rule that only sets attributes doesn't keep the span. - An errored span is held with its trace instead, so trace rules such as **Drop Traces Without Errors** can see the error. The span is dropped when the trace is sent, unless a keep rule matches it. For example, a keep rule can use **Has Error** is true. ## Keep rules A synchronous span is kept if any keep rule matches it. SpanSlice checks the service's keep rules first, then the project's. Keep rules can test what's known once the span ends, without the rest of its trace: | Condition | Operators | | ----------------------------------------------------------- | ---------------------------------------------------- | | Span Name, Library Name, Span Attribute, Resource Attribute | as in [rules](/concepts/rules/#conditions) | | Span Kind | is, is not, in, not in | | Span Duration | =, >, >=, \<, \<=, between | | Has Error | is true, is false | | Is Root Span, Is Child Span | none: whether the span has a parent in this process | | Has Child Spans | none: whether a child of the span will still be sent | **Has Child Spans** is only available in keep rules. SpanSlice decides it when the span ends, from the children still sent by then: - A child dropped along with its own subtree doesn't count. - A child dropped on its own counts through its kept children. In the animation, `render` is dropped once `escape`, its only child, is dropped. New projects start with two keep rules: - **Is Root Span**, so a trace's root is never dropped and the trace isn't split. - **Has Child Spans**, so a synchronous span that starts asynchronous work stays as that work's parent. ## Turning it off The **Drop Synchronous Spans** switch on the Synchronous Span Handling page turns dropping off for a service in an environment. Every synchronous span is then kept, and it goes through your rules like any other span. # Stuck spans Source: https://docs.spanslice.com/concepts/stuck-spans/ A span is sent only when it ends. A query waiting on a lock, or a call to a service that never answers, can stay open for minutes. A span that never ends is never seen. **Stuck Span Detection** reports a span while it's still open, once it has been open longer than a **Stuck Span Timeout**. ## Timeouts and handlers - A **Stuck Span Timeout** is how long a span can stay open before it counts as stuck. You set it in seconds or minutes. New projects have no timeouts, so nothing is checked until you add one. - Each timeout has an ordered list of **handlers**. A handler has conditions, and an action for a span that matches them. A handler with no conditions matches every span that's stuck for that long. A stuck span hasn't ended, so its duration, error status and end attributes aren't known yet. Handlers use the same conditions as rules, with the fields known while a span is open: **Service Name**, **Span Name**, **Library Name**, **Span Kind**, **Span Attribute** (as set so far), **Resource Attribute**, **Is Root Span** and **Is Child Span**. As with rules, you set timeouts per service or as project defaults, and switch them on per environment. A service's handlers are tried before the project's. ## What a handler does - **Report once, then drop** (the default) takes one snapshot at the timeout. The span is dropped when it ends. - **Report then…** takes one snapshot at the timeout. **Report after… repeating N times, then…** takes N snapshots, one at each timeout. After that, the handler does one of these: - **Continue reporting indefinitely**: a snapshot at each timeout for as long as the span stays open. The span is kept. - **Continue reporting N more times**: N more snapshots. The span is dropped when it ends. - **Stop reporting, then drop**: no more snapshots. The span is dropped when it ends. - **Silently drop**: no snapshot. The span is dropped when it ends. When a span is dropped, its children move up to its parent, as with **Drop Span**. SpanSlice checks open spans every 5 seconds, so a snapshot can arrive up to 5 seconds after its timeout. ## Snapshots A snapshot is a copy of the span as it looks right now. It's named ` (incomplete)`, ends when it's taken, and has its own span ID, so it never collides with the real span. It carries the span's attributes, with redactions applied, plus these: | Attribute | Meaning | | -------------------------------- | ------------------------------------------------------------ | | `spanslice.stuck.is_snapshot` | `true` | | `spanslice.stuck.duration_ms` | how long the span had been open | | `spanslice.stuck.reported_count` | 1 on the first snapshot, 2 on the next, … | | `spanslice.stuck.source_span_id` | the real span's ID, to find it once it ends | | `spanslice.stuck_by` | the handler that took the span; the real span carries it too | SpanSlice sends snapshots as it takes them, outside the trace. Rules and sampling don't apply to them, and they carry no `SampleRate`. In Live Tail, the **Stuck** filter shows them. ## Several timeouts SpanSlice checks timeouts from shortest to longest. When a span reaches a timeout, that timeout's handlers are tried in order. The first handler that matches takes the span over from the handler in charge so far, and it counts its own snapshots from one. If nothing matches, the earlier handler stays in charge. A span that no handler ever matches is kept and never reported. The handler in charge reports once per its own timeout. For example, take a 30-second timeout whose handler reports `pg.query` indefinitely, and a 5-minute timeout whose handler reports any span once and drops it. A query open for six minutes is reported at 30 seconds, then every 30 seconds up to 4½ minutes. At 5 minutes, the second handler reports it once more, and the span is dropped when it ends. A trace with a stuck span open is held like any other trace. It's [sent early](/concepts/rules/#spans-are-held-until-the-trace-is-decided) once it's 120 seconds old. # Metrics Source: https://docs.spanslice.com/concepts/metrics/ A metric is a stream of measurements with a name, such as `http.server.request.duration`. Each distinct set of attribute values is a **series**. For example, `http.route=/orders` and `http.route=/cart` are two series of one metric. The SDK combines measurements in memory and exports them once per **interval**. Each series sends one value per interval, however many measurements it received. **Metrics › Captured** lists what each service records, with each metric's kind, series and attribute keys. ## Kinds A metric's kind decides how its measurements combine. ### Counter A total that only goes up, such as requests served. Each measurement adds to it, and each interval exports the total so far. Graph its rate. ### Up-down counter A total that goes down as well as up, such as open connections or queued jobs. Each measurement adds or takes away. ### Gauge A reading taken now and then, such as CPU or memory use. Readings aren't added together. Each interval exports only the latest one. ### Histogram A distribution, such as request durations. Each value is counted in the bucket it falls into. The count, sum, min and max are kept alongside, so you can estimate percentiles. ## Views A **View** reshapes a service's metrics before they're exported. A View matches metrics by name and scope (with `*` and `?` globs), kind, and unit, then changes them. You set Views per service or as project defaults, and switch them on per environment. A View's name is optional. An unnamed View uses a title based on what it does, such as `v8js.gc.*: drop`. ### How Views combine Views apply in order: a service's Views come before the project's. Each setting comes from the first matching View that sets it. A service View can therefore override one part of a project View and inherit the rest. If any matching View drops a metric, the metric is dropped. ### Drop metric Sends nothing for matching metrics. ### Attributes **Keep only** the listed keys, or **Drop** them. Series that differ only in removed keys merge into one, and their values combine. Dropping keys is the main way to cut series. For example, a `user.id` on a request counter creates a series per user. ### Value mapping Rewrites an attribute's values, so fewer distinct values and fewer series are sent. Series that end up with the same values merge. - **Status class** turns a status code into its class: `404` → `4xx`. - **Replace** rewrites values with a regex. For example, it can turn IDs in a path: `/users/\d+` → `/users/:id`. - **Allow list** keeps the listed values and turns any other into one catch-all, `_OTHER` unless you name another. ### Sum merged series Attributes and value mappings merge series. For counters, up-down counters and histograms that the app records directly, a merged series combines the measurements. Observable instruments work differently. They report one value per series each time they're collected. By default, a merged series keeps just one of those values. **Sum merged series** makes a merged series report the total of its values. For example, `v8js.memory.heap.space.available_size` reports one gauge per heap space. If you drop `v8js.heap.space.name` with this on, you get the total heap available. Without it, you get whichever space was read last. Observable counters and up-down counters always sum. The setting matters only for observable gauges, where a total isn't always meaningful. Per-core CPU use, for example, doesn't add up to anything. To get one value you choose, use a [filter](#filter) instead. ### Filter A filter sends only the measurements whose attribute has one of the values you list, and discards the rest. A measurement without the attribute is also discarded. With several keys, a measurement must match each one. Filters run before every other setting, so a View can keep a few values and then sum them. For example, to send only the old generation's heap, filter `v8js.heap.space.name` to `old_space`, then drop `v8js.heap.space.name`. On **Metrics › Captured**, an attribute's **Drop attribute** menu has two choices: - **Sum the values** (**Combine the values** for a histogram) drops the attribute and merges its series. On a gauge, it also turns on Sum merged series, so it's offered only for gauges the SDK reports as observable. - **Keep only…** filters the attribute to the values you pick. Keep one and the attribute is dropped too, so the metric has one series. Keep several and each keeps its own series. The same dialog has a checkbox, **Sum the rest into one series** (for a histogram, **Combine the rest into one histogram**). It keeps the values you pick and sends the others as one `_OTHER` series instead of discarding them. It uses an allow-list value mapping. On a gauge, it sums with Sum merged series, so the gauge must be observable. Once a View drops an attribute, its row says how the values combine, such as "dropped by a View · values summed". ### Aggregation Changes how measurements combine. - **Explicit histogram** counts values in buckets, with boundaries you choose. - **Exponential histogram** uses buckets whose bounds grow by powers of two. It rescales them to fit the values, up to a maximum count of 160 by default. You don't choose boundaries. - **Sum** keeps only the running total. - **Last value** keeps only the latest value in each interval. ### Series limit Caps the number of series a metric keeps. Once the cap is reached, every new combination of attributes goes into one series marked `otel.metric.overflow=true`. An unexpected high-cardinality attribute therefore can't grow the metric without bound. ### Rename Exports the metric under a new name or description. To rename a metric, the View must match one exact name, with no `*` or `?`. ## Span metrics A **span metric** is a counter or histogram built from spans. SpanSlice records it for every matching span as the span ends, or once per trace when the root span ends. It records before sampling and drop rules run, so it counts everything the service did, not just what was kept. | Record for | Value | Records | | ---------- | ----------------------- | -------------------------------------------------- | | Each span | Count | 1 per matching span | | Each span | Duration | the span's duration, in ms | | Each span | Attribute value | a numeric attribute; spans without it record none | | Each trace | Count of matching spans | how many matching spans ended before the trace did | | Each trace | Trace duration | the root span's duration | **Group by** splits a span metric into series by attribute keys, or by `span.name`, `span.kind` and `span.status`. SpanSlice reads these from the span, or from the root span for a per-trace metric. Span metrics appear on Captured under the `spanslice.span_metrics` scope. Views can reshape them like any other metric. # Using the API Source: https://docs.spanslice.com/api/ The SpanSlice API lets scripts, CI jobs and agents do what the app does with your rules. It reads organizations, projects, environments and services. It creates, edits, reorders and switches rules. In environments that require commit, it reviews and commits pending changes. Agents can call the same operations as MCP tools. See [For agents](/api/agents/). ## Base URL ```text https://api.spanslice.com ``` Operations live under `/v1`, and they send and receive JSON. The [reference](/api/reference/) lists every operation. It's generated from the OpenAPI 3.1 spec at `https://api.spanslice.com/v1/openapi.json`, which needs no token. ## Make an access token Create a token in the app under **Settings › Access tokens**. Give it a name, a role, and an expiry: 30 days, 90 days, a year, or none. SpanSlice shows the token once, when you create it, and keeps only its hash. You revoke a token on the same page. There are two kinds: | | Personal (`ss_pat_…`) | Organization (`ss_org_…`) | | ------------------- | ------------------------------------------------- | --------------------------------------- | | Made by | anyone in the org, for themselves | admins and owners | | Acts as | you, with the lower of your role and the token's | the organization, with the token's role | | Commits are made by | you | no one in particular (`by` is `null`) | | Stops working | when it expires, is revoked, or you leave the org | when it expires or is revoked | A token belongs to one organization and can't reach anything outside it. The SDK's API keys (`ss_…`, set as `SPANSLICE_API_KEY`) are a different credential. The API refuses them with a 401. ## A first request Send the token as a bearer token. `getMe` describes the token, so it's a good first call: ```sh export SPANSLICE_TOKEN=ss_pat_… curl https://api.spanslice.com/v1/me \ -H "Authorization: Bearer $SPANSLICE_TOKEN" ``` ```json { "token": { "name": "Rules agent", "kind": "personal", "role": "member", "organization": "snugghome", "expires_at": "2027-01-06T14:03:12.000Z", "created_at": "2026-10-08T14:03:12.000Z" }, "user": { "name": "Ada", "email": "ada@snugghome.com" } } ``` The `token.organization` value is the slug that other operations take. To list its projects: ```sh curl https://api.spanslice.com/v1/orgs/snugghome/projects \ -H "Authorization: Bearer $SPANSLICE_TOKEN" ``` ```json { "data": [ { "slug": "snugghome-app", "name": "SnuggHome App", "organization": "snugghome", "created_at": "2026-09-18T12:00:00.000Z" } ], "next_cursor": null } ``` ## Roles Each operation needs a role, which the reference shows. Reads need **viewer**. Changing rules and committing need **member**. No operation needs more than that, so a token never needs **admin** to use the API. A token whose role is too low gets a 403. If the token can't reach something, including anything in another organization, the API returns a 404, as if it didn't exist. ## Slugs and rule ids Organizations, projects, environments and services are addressed by the slugs in their app URLs. A slug that a project or organization had before a rename still finds it. Rules have ids such as `rule_RVeVNOTP`. An id stays the same across environments and renames. Wherever an operation takes a rule, it also takes the keys that spans carry in their `spanslice.rules` attribute, one per environment. So from a span in your observability backend, `getRule` leads straight to the rule that changed it. ## Lists Lists return `{ data, next_cursor }`. Pass `limit` (1 to 200, default 100) to set the page size. To get the next page, pass `next_cursor` back as `cursor`. It's `null` on the last page. ```sh curl "https://api.spanslice.com/v1/orgs/snugghome/projects/snugghome-app/rules?limit=50&cursor=$NEXT_CURSOR" \ -H "Authorization: Bearer $SPANSLICE_TOKEN" ``` ## Versions and `If-Match` Each rule has a `version`, which goes up with every edit to what the rule does. When you update a rule, send the version you read as `If-Match`. If someone changed the rule since then, nothing is written and you get a 412. Read the rule again, and reapply your change. ```sh curl -X PATCH https://api.spanslice.com/v1/orgs/snugghome/projects/snugghome-app/rules/rule_RVeVNOTP \ -H "Authorization: Bearer $SPANSLICE_TOKEN" \ -H 'If-Match: "1"' \ -H 'Content-Type: application/json' \ -d '{ "name": "Drop health and readiness checks" }' ``` `If-Match` is optional, but without it you can overwrite someone else's edit. Switching a rule on or off (`setRuleEnabled`) isn't versioned. ## Changing rules in environments that require commit A project's rules are shared by all its environments. In an environment that applies changes as they're made, the SDKs pick up a new rule with their next config. In an environment that **requires commit**, the SDKs keep running the latest commit. A change waits there as a pending change until someone commits it. To turn this on, use the environment's **Require commit** switch in the app. Here's the whole flow with curl. Set the common parts once: ```sh API=https://api.spanslice.com/v1/orgs/snugghome/projects/snugghome-app AUTH="Authorization: Bearer $SPANSLICE_TOKEN" ``` ### 1. Check which environments require commit ```sh curl "$API/environments" -H "$AUTH" ``` ```json { "data": [ { "slug": "staging", "name": "Staging", "description": null, "requires_commit": false, "position": 0 }, { "slug": "production", "name": "Production", "description": null, "requires_commit": true, "position": 1 } ], "next_cursor": null } ``` ### 2. Create a rule ```sh curl -X POST "$API/rules" -H "$AUTH" -H 'Content-Type: application/json' -d '{ "name": "Drop health checks", "stage": "created", "target": "root", "when": { "type": "group", "operator": "or", "children": [ { "type": "clause", "subject": "spanAttribute", "argument": "http.route", "operator": "is", "value": "/healthz" }, { "type": "clause", "subject": "spanAttribute", "argument": "http.route", "operator": "is", "value": "/readyz" } ] }, "then_actions": [{ "action": "dropTrace" }] }' ``` The response is the rule as written, with its `id`, `version`, and per-environment `keys`. Staging runs the rule from now on. Production doesn't run it yet. `getRuleLanguage` (`GET /v1/rule-language`) lists everything that `when` and `then_actions` can express: each condition subject with its operators and value shapes, each action with its fields, and example rules. [How rules run](/concepts/rules/) and [Actions](/concepts/actions/) explain what they do. ### 3. Review what committing would change ```sh curl "$API/environments/production/pending" -H "$AUTH" ``` ```json { "environment": "production", "requires_commit": true, "working_version": "5f0c2e9a41d3b7c8", "committed": { "message": "Sample checkout at 1 in 10", "created_at": "2026-10-07T09:12:44.000Z", "by": "Ada" }, "changes": [ { "id": "WyJydWxlIiwiYWRkZWQiLDE3LG51bGxd", "kind": "rule", "change": "added", "rule": "rule_RVeVNOTP", "services": ["Api", "Main"], "after": { "key": "ZWMVUY0p", "name": "Drop health checks", "stage": "created", "target": "root" }, "revertible": true } ] } ``` `changes` lists every difference between what production runs now and what it would run after a commit. That includes changes other people made in the app, such as instrumentation, metrics, or destinations, not only yours. ### 4. Commit Send back the `working_version` you reviewed: ```sh curl -X POST "$API/environments/production/commits" -H "$AUTH" -H 'Content-Type: application/json' \ -d '{ "working_version": "5f0c2e9a41d3b7c8", "message": "Drop health checks" }' ``` ```json { "message": "Drop health checks", "created_at": "2026-10-08T14:20:01.000Z", "by": "Ada" } ``` Production's SDKs now run every pending change. If anything changed after you read `working_version`, nothing is committed, and you get a 409. Review the pending changes again, then commit the new `working_version`. To drop one change instead, revert it, sending the same `working_version`: ```sh curl -X POST "$API/environments/production/pending/WyJydWxlIiwiYWRkZWQiLDE3LG51bGxd/revert" -H "$AUTH" \ -H 'Content-Type: application/json' -d '{ "working_version": "5f0c2e9a41d3b7c8" }' ``` Reverting puts the setting back the way the latest commit has it. Rules are shared, so other environments see the revert too, the same as when you revert in the app. ## Errors Errors are [RFC 9457](https://www.rfc-editor.org/rfc/rfc9457) problems (`application/problem+json`). Each has a stable `code` to branch on, and a `detail` that says what to change. [Errors](/api/errors/) lists every code. ## The spec `https://api.spanslice.com/v1/openapi.json` describes every operation, parameter and object, with examples. It needs no token. Use it to generate a client, import the API into an HTTP tool, or give it to an agent. The [reference](/api/reference/) on this site is built from the same spec. # For agents Source: https://docs.spanslice.com/api/agents/ Every API operation is also an MCP tool. An agent such as Claude Code can use these tools to find the rule that changed a span, write and edit rules, and prepare a commit for you to review. ## Connect over MCP The server is at `https://api.spanslice.com/mcp`. It speaks streamable HTTP and takes the same bearer [access token](/api/#make-an-access-token) as the API. It's stateless. Each request stands alone, and there's no server-sent event stream. ### Claude Code ```sh claude mcp add --transport http spanslice https://api.spanslice.com/mcp \ --header "Authorization: Bearer ss_pat_…" ``` `claude mcp add` stores the token in your Claude Code settings, not in the repository. ### Other clients Any client that supports streamable HTTP with a custom header can connect with the same URL and header. Most take a config like this: ```json { "mcpServers": { "spanslice": { "type": "http", "url": "https://api.spanslice.com/mcp", "headers": { "Authorization": "Bearer ${SPANSLICE_TOKEN}" } } } } ``` If you commit a file like this (such as Claude Code's `.mcp.json`), read the token from an environment variable, as above, rather than writing it in. The server accepts bearer tokens only, not OAuth. A client that adds remote servers only through OAuth can't connect directly. ## Tools There's one tool per operation, named by its `operationId`: `getMe`, `listRules`, `createRule`, and so on. Each tool's description is the operation's description from the [reference](/api/reference/), plus the role it needs. Its arguments combine the operation's path and query parameters with its body fields. Headers become snake_case arguments, so `If-Match` is `if_match`. Rule conditions and actions make up most of the API's schema. To keep the tool list short, the rule tools don't spell them out. They point the agent to `getRuleLanguage` instead. That tool returns every condition subject with its operators and value shapes, every action with its fields, example rules, and the exact JSON Schemas. Tools carry hints that clients use to decide what to confirm. Every read (`get…`, `list…`) is read-only and idempotent. The table shows the rest: | Tool | Read-only | Destructive | Idempotent | | ------------------- | --------- | ----------- | ---------- | | `createRule` | no | no | no | | `updateRule` | no | no | no | | `deleteRule` | no | yes | yes | | `setRuleEnabled` | no | no | yes | | `reorderRules` | no | no | yes | | `commitEnvironment` | no | yes | no | | `revertChange` | no | yes | no | A failed call returns a tool result marked as an error. Its text is the same [problem](/api/errors/) that the API would send, so the agent can read `detail` and fix its request. ## A workflow that works The server's instructions give agents this outline: 1. `getMe`, for the token's organization and role. 2. `listProjects`, then `listEnvironments` (note which ones have `requires_commit`) and `listServices`. 3. `getRuleLanguage`, before writing any rule. 4. `listRules` to see what runs. To explain a span, take the keys in its `spanslice.rules` attribute and call `getRule` with each. 5. `createRule` or `updateRule`, sending the `version` it read as `if_match`. 6. `getPendingChanges` for each environment that requires commit. Show the changes to a person. 7. `commitEnvironment` with the `working_version` it reviewed, only once a person has approved it. Here's an example prompt: > Health checks from the api service are flooding production. Write a rule that drops them, show me the pending changes > for production, and wait for my go-ahead before you commit. ## Keep it safe - **Use the lowest role that works.** A **viewer** token can answer questions about rules but change nothing. Writing rules and committing need **member**. Nothing needs more. - **Pick the right kind of token.** Use a personal token for an agent you run yourself. It acts as you, its commits show your name, and it stops working if you leave. Use an organization token for shared automation that shouldn't depend on one person. - **Set an expiry**, and revoke tokens you no longer use under **Settings › Access tokens**. - **Require commit in production.** Then an agent's edits wait as pending changes, and production keeps running its last commit. A member token can still commit, though. Either have your client ask before it runs `commitEnvironment` (the tool is marked destructive), or review and commit in the app yourself. - **Keep tokens out of prompts and repositories.** Pass them through your client's settings or an environment variable. ## Without MCP An agent that can make HTTP requests can use the API from the spec alone. The spec is at `https://api.spanslice.com/v1/openapi.json` and needs no token. Its descriptions and examples are written to be enough on their own. Give the agent the token in an environment variable, such as `SPANSLICE_TOKEN`, and have it send `Authorization: Bearer $SPANSLICE_TOKEN`. For the rest of these docs, [`llms.txt`](/llms.txt) lists every page, and [`llms-full.txt`](/llms-full.txt) has their full text. # Errors Source: https://docs.spanslice.com/api/errors/ Every error from the API is an [RFC 9457](https://www.rfc-editor.org/rfc/rfc9457) problem, sent as `application/problem+json`: ```json { "type": "https://docs.spanslice.com/api/errors#invalid_request", "title": "Invalid request", "status": 400, "detail": "The request body is invalid at /stage: Invalid option: expected one of \"created\"|\"completed\"", "code": "invalid_request", "errors": [ { "detail": "Invalid option: expected one of \"created\"|\"completed\"", "pointer": "/stage" }, { "detail": "At least 1", "pointer": "/then_actions/0/oneIn" } ] } ``` | Field | Meaning | | -------- | ------------------------------------------------------------------------------------- | | `type` | A link to this page. Its fragment is the `code`. | | `title` | A short summary of the kind of problem. | | `status` | The HTTP status. | | `detail` | What went wrong with this request, and how to fix it where possible. | | `code` | Stable and machine-readable. Branch on this, not on `title` or `detail`. | | `errors` | For `invalid_request`, each problem found, so you can fix them all at once. Optional. | Each item in `errors` has a `detail` and points to the problem with one of these fields: - `pointer`: a [JSON Pointer](https://www.rfc-editor.org/rfc/rfc6901) into the request body. `/then_actions/0/oneIn` is the `oneIn` field of the first action. - `parameter`: a path or query parameter, such as `limit`. - `header`: a request header, such as `if-match`. MCP tools return the same problem as the text of a result marked as an error. ## invalid_request **400.** The request doesn't fit the operation. The body might not be valid JSON, a field might be missing or the wrong type, or a parameter might be out of range. This code also covers requests the operation can't carry out. For example: a service slug the project doesn't have, a commit to an environment that doesn't require commit, or a revert of an organization-wide setting. `errors` lists each problem it found. Fix the request. Sending it again unchanged fails the same way. ## unauthorized **401.** The request has no access token, or the token is unknown, expired, or revoked. An SDK API key (`ss_…`) also gets this error. The API accepts only access tokens (`ss_pat_…`, `ss_org_…`). The response includes a `WWW-Authenticate: Bearer` header. Send `Authorization: Bearer `. If the token expired or was revoked, create a new one under **Settings › Access tokens**. ## forbidden **403.** The token's role is too low for the operation, such as a viewer token creating a rule. A personal token acts with the lower of its own role and yours, so it can lose access when your role changes. Use a token with the role that the [reference](/api/reference/) lists for the operation. ## not_found **404.** The thing doesn't exist, or the token can't reach it. Other organizations, and everything in them, return 404 rather than 403, as if they didn't exist. A path that names no operation also returns 404. Check the slugs and IDs. `getMe` returns the token's organization, and the list operations return the rest. ## method_not_allowed **405.** The path exists, but not with this HTTP method. Check the method in the [reference](/api/reference/). ## conflict **409.** The request was made against a state that has since changed. `commitEnvironment` and `revertChange` send this when the environment's settings changed after the `working_version` you sent. Nothing is committed or reverted, so you never act on changes you haven't reviewed. Call `getPendingChanges` again, review the changes, and retry with the new `working_version`. ## precondition_failed **412.** The `If-Match` version is stale: the rule changed after you read it. Nothing was written. Read the rule again, reapply your change to it, and send its new `version`. ## payload_too_large **413.** The request body is over 1 MB. ## internal_error **500.** Something went wrong on SpanSlice's side. SpanSlice logs the error. Retrying may help. Before you retry a write, read what it changes to see whether it took effect. ## upstream_error **502.** A service that SpanSlice depends on either failed or didn't respond. Retry after a short wait. # API reference Every operation, by tag. The request and response schemas are in the OpenAPI spec at https://api.spanslice.com/v1/openapi.json. ## Account Source: https://docs.spanslice.com/api/reference/account/ Who a credential acts as. ### Describe the access token `GET https://api.spanslice.com/v1/me` (`getMe`, viewer or higher) Who this request acts as: the token, its organization and role, and for a personal token the person it belongs to. Call it first to check a token works and to find the organization slug the other operations take. ## Organizations Source: https://docs.spanslice.com/api/reference/organizations/ Organizations you belong to. ### List organizations `GET https://api.spanslice.com/v1/orgs` (`listOrgs`, viewer or higher) The organizations this token reaches: an access token reaches just its own, so this is one item. ### Get an organization `GET https://api.spanslice.com/v1/orgs/{org}` (`getOrg`, viewer or higher) One organization, with your role in it as this token acts. ## Projects Source: https://docs.spanslice.com/api/reference/projects/ Projects, their environments and their services. ### List projects `GET https://api.spanslice.com/v1/orgs/{org}/projects` (`listProjects`, viewer or higher) An organization's projects. Rules, environments and services all belong to a project. ### Get a project `GET https://api.spanslice.com/v1/orgs/{org}/projects/{project}` (`getProject`, viewer or higher) One project. A slug the project or its organization had before a rename still finds it. ### List environments `GET https://api.spanslice.com/v1/orgs/{org}/projects/{project}/environments` (`listEnvironments`, viewer or higher) A project's runtime environments in order. Check `requires_commit` before changing rules: in an environment that requires commit, changes wait for a commit before its SDKs see them. ### Get an environment `GET https://api.spanslice.com/v1/orgs/{org}/projects/{project}/environments/{environment}` (`getEnvironment`, viewer or higher) One runtime environment of a project: whether it requires commit, and so whether changes reach its SDKs at once or wait as pending changes. ### List services `GET https://api.spanslice.com/v1/orgs/{org}/projects/{project}/services` (`listServices`, viewer or higher) A project's services, by name, with the environments each is deployed to. A rule can apply to the whole project or to one service. ## Rules Source: https://docs.spanslice.com/api/reference/rules/ Span rules: conditions on a span and the actions to take when it matches. They are what SpanSlice runs in your SDKs. ### List rules `GET https://api.spanslice.com/v1/orgs/{org}/projects/{project}/rules` (`listRules`, viewer or higher) A project's span rules, in the order they run: rules with stage `created` before rules with stage `completed`, and within a stage each service's own rules before the project's. ### Create a rule `POST https://api.spanslice.com/v1/orgs/{org}/projects/{project}/rules` (`createRule`, member or higher) Adds a rule at the end of its list (stage and service). It runs everywhere it applies at once, except in environments that require commit, where it waits as a pending change until someone commits. ### Get a rule `GET https://api.spanslice.com/v1/orgs/{org}/projects/{project}/rules/{rule}` (`getRule`, viewer or higher) One rule, by its id or by a key from a span's `spanslice.rules` attribute: to find what changed a span, look up each key it carries. ### Update a rule `PATCH https://api.spanslice.com/v1/orgs/{org}/projects/{project}/rules/{rule}` (`updateRule`, member or higher) Changes the fields sent and leaves the rest. Moving a rule to another stage or service puts it at the end of that list; moving it to one service keeps only that service's switches. Send `If-Match` with the version you read so you never overwrite someone else's edit. ### Delete a rule `DELETE https://api.spanslice.com/v1/orgs/{org}/projects/{project}/rules/{rule}` (`deleteRule`, member or higher) Deletes the rule and its history. In environments that require commit, SDKs keep running it until the deletion is committed. To stop it somewhere without deleting it, use setRuleEnabled. ### Switch a rule on or off `PATCH https://api.spanslice.com/v1/orgs/{org}/projects/{project}/rules/{rule}/enabled` (`setRuleEnabled`, member or higher) Switches the rule on or off for the (service, environment) pairs named, leaving the others as they are. A pair must be a deployment the rule applies to. This is not a versioned edit. ### Reorder a list of rules `PUT https://api.spanslice.com/v1/orgs/{org}/projects/{project}/rules/order` (`reorderRules`, member or higher) Sets the order of one list: the rules of one stage at project scope (`service: null`) or for one service. `order` must name every rule in that list exactly once. ### Describe the rule language `GET https://api.spanslice.com/v1/rule-language` (`getRuleLanguage`, viewer or higher) Everything a rule's `when` and `then_actions` can say: each condition subject with its operators and value shapes, each action with its fields, example rules, and the exact JSON Schemas. Read it before writing a rule. ## Commits Source: https://docs.spanslice.com/api/reference/commits/ Environments that require commit run their latest commit. Changes wait as pending changes until someone commits them. ### List pending changes `GET https://api.spanslice.com/v1/orgs/{org}/projects/{project}/environments/{environment}/pending` (`getPendingChanges`, viewer or higher) What committing would change in an environment that requires commit: each difference between what its SDKs run (the latest commit) and the settings as they are now. Empty for an environment that applies changes at once. Review these, then commitEnvironment with `working_version`. ### Commit pending changes `POST https://api.spanslice.com/v1/orgs/{org}/projects/{project}/environments/{environment}/commits` (`commitEnvironment`, member or higher) Makes the environment's SDKs run its settings as they are now: every pending change at once. Only for environments that require commit. Commits are how changes reach production there, so commit only what a person asked for or approved. ### Revert a pending change `POST https://api.spanslice.com/v1/orgs/{org}/projects/{project}/environments/{environment}/pending/{change}/revert` (`revertChange`, member or higher) Undoes one pending change, putting that setting back as the latest commit has it. Other environments that share the setting (rules are shared) change too, as they would in the app.