Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion bin/observe-cli-resources.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"_comment": "Resources to keep in sync with the latest CLI version. Consumed by bin/update-observe.js, which fetches the live config for each resource and only patches the version-relevant fields (in-place: any X.Y.Z literal found in the name, raw SLI expression, or version filter is rewritten). For alerts and error projects, versionFilterColumn names the filter holding the CLI version.",
"_comment": "Resources that track the newest CLI release line. Consumed by bin/update-observe.js, which fetches the live config for each resource and only patches the version-relevant fields to match the line (bin/observe-version.js): versions in the name become X.Y.x, cli_version matchers in a raw SLI expression or histogram filters become the regex X[.]Y[.][0-9]+, and the version filter of an alert or error project starts with X.Y. SLIs also drop the job matcher on @shopify/(app|store):.*, and a traffic guard that multiplies becomes a filter. For alerts and error projects, versionFilterColumn names the filter holding the CLI version.",
"endpoint": "https://shopify-monitoring.shopifycloud.com/query",
"service": "cli",
"resources": [
Expand Down
128 changes: 128 additions & 0 deletions bin/observe-version.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
// The release-line forms bin/update-observe.js writes into the CLI's Observe resources. They track a
// minor's whole line, X.Y.x, so its patches need no Observe update: only a new minor or major moves them.

const minorVersionPattern = /^(\d+)\.(\d+)\.0$/

// The SLI forms also make two changes that leave an SLI without them as it is. The SLOs no longer select commands
// by this job matcher, so the forms drop it and keep every other job matcher.
const staleJobFilter = {key: 'job', op: '=~', value: '@shopify/(app|store):.*'}
const staleJobMatcher = /job\s*=~\s*"@shopify\/\(app\|store\):\.\*"/.source
// The matcher with the comma that joins it to a neighbour, wherever it sits in a selector.
const staleJobMatcherInSelector = new RegExp(
`${staleJobMatcher}\\s*,\\s*|\\s*,\\s*${staleJobMatcher}|${staleJobMatcher}`,
'g',
)
const isStaleJobFilter = (filter) =>
filter.key === staleJobFilter.key && filter.op === staleJobFilter.op && filter.value === staleJobFilter.value

// A traffic guard that multiplies, `ratio * on() (sum(rate(cli_commands_total{...}[w])) > n)`, keeps the rate's
// value, since a comparison without `bool` keeps its left side, so `1 - ratio * ...` counts errors a second rather
// than their share. The forms make it a filter, `and on()`, so the SLI is the ratio while the guard holds.
const multipliedTrafficGuard =
/\*(\s*on\(\)\s*\(\s*sum\(rate\(cli_commands_total\{[^}]*\}\s*\[\w+\]\)\)\s*>\s*[\d.]+\s*\))/g

/**
* The release line a minor or major version starts, or undefined for a patch or anything else.
*
* @param {string} version
* @returns {{major: string, minor: string} | undefined}
*/
export function releaseLine(version) {
const match = minorVersionPattern.exec(version)
return match ? {major: match[1], minor: match[2]} : undefined
}

/**
* Why update-observe takes no version but a minor or major, X.Y.0. A patch's line may still be pinned to one
* version, from before the resources tracked lines, so the reason says how to move them onto the line.
*
* @param {string} version
* @returns {string}
*/
export function versionRefusal(version) {
const patch = /^(\d+)\.(\d+)\.\d+$/.exec(version)
if (!patch) return `Version must be a minor or major release, X.Y.0 (got: ${version})`
const lineStart = `${patch[1]}.${patch[2]}.0`
return `${version} is a patch: the resources track the ${patch[1]}.${patch[2]} line, so it needs no update. Run this for a minor or major release, X.Y.0. If the resources still pin one version, run this once with --version=${lineStart}.`
}

/**
* The PromQL regex that matches every version of a line: `[.]` keeps backslashes out of PromQL strings.
*
* @param {{major: string, minor: string}} line
* @returns {string}
*/
export function lineRegex(line) {
return `${line.major}[.]${line.minor}[.][0-9]+`
}

/**
* A resource name with each version in it, such as `5.2.0`, `v4.9.4` or `5.1.x`, replaced by the line,
* `5.2.x`, keeping a leading `v`.
*
* @param {string} name
* @param {{major: string, minor: string}} line
* @returns {string}
*/
export function lineName(name, line) {
return name.replace(
/(?<![\w.])(v?)\d+\.\d+\.(?:\d+|x|\*)(?![\w.])/g,
(_version, prefix) => `${prefix}${line.major}.${line.minor}.x`,
)
}

/**
* A PromQL expression with each `cli_version` matcher, exact or a regex, matching the line instead. It also drops
* the stale job matcher and makes a multiplied traffic guard a filter.
*
* @param {string} expression
* @param {{major: string, minor: string}} line
* @returns {string}
*/
export function lineExpression(expression, line) {
return expression
.replace(staleJobMatcherInSelector, '')
.replace(multipliedTrafficGuard, 'and$1')
.replace(/cli_version\s*=~?\s*"[^"]*"/g, `cli_version=~"${lineRegex(line)}"`)
}

/**
* A histogram SLI's metric filters with the `cli_version` filter matching the line, and without the stale job
* filter.
*
* @param {{key: string, op: string, value: string}[]} filters
* @param {{major: string, minor: string}} line
* @returns {{key: string, op: string, value: string}[]}
*/
export function lineHistogramFilters(filters, line) {
return filters
.filter((filter) => !isStaleJobFilter(filter))
.map((filter) =>
filter.key === 'cli_version' && ['=', '=~'].includes(filter.op)
? {...filter, op: '=~', value: lineRegex(line)}
: filter,
)
}

/**
* An error filter, as alerts and error projects store it (JSON with nested filter groups), with the
* filters on `column` matching every version that starts with the line, `5.2.`.
*
* @param {string} filterJson
* @param {string} column
* @param {{major: string, minor: string}} line
* @returns {string}
*/
export function lineErrorFilters(filterJson, column, line) {
const patchGroup = (group) => ({
...group,
filters:
group.filters?.map((filter) =>
filter.column === column && ['=', 'starts-with'].includes(filter.op)
? {...filter, op: 'starts-with', value: `${line.major}.${line.minor}.`}
: filter,
) ?? group.filters,
filter_groups: group.filter_groups?.map(patchGroup) ?? group.filter_groups,
})
return JSON.stringify(patchGroup(JSON.parse(filterJson)))
}
187 changes: 187 additions & 0 deletions bin/observe-version.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
import assert from 'node:assert/strict'
import {test} from 'node:test'

import {
lineErrorFilters,
lineExpression,
lineHistogramFilters,
lineName,
lineRegex,
releaseLine,
versionRefusal,
} from './observe-version.js'

const line52 = releaseLine('5.2.0')
const line53 = releaseLine('5.3.0')

test('a minor or major release starts a line, and a patch does not', () => {
assert.deepEqual(releaseLine('5.2.0'), {major: '5', minor: '2'})
assert.deepEqual(releaseLine('6.0.0'), {major: '6', minor: '0'})
assert.equal(releaseLine('5.2.1'), undefined)
assert.equal(releaseLine('5.2'), undefined)
assert.equal(releaseLine('0.0.0-nightly-20261204061218'), undefined)
assert.equal(lineRegex(line52), '5[.]2[.][0-9]+')
})

test("a patch is refused with how to move a line that still pins one version, and a non-release isn't a version", () => {
assert.equal(
versionRefusal('5.2.1'),
'5.2.1 is a patch: the resources track the 5.2 line, so it needs no update. Run this for a minor or major release, X.Y.0. If the resources still pin one version, run this once with --version=5.2.0.',
)
assert.equal(versionRefusal('5.2'), 'Version must be a minor or major release, X.Y.0 (got: 5.2)')
})

test('names show the line, keeping a leading v, and a later minor moves them on', () => {
assert.equal(lineName('Correctness (Version 5.2.0)', line52), 'Correctness (Version 5.2.x)')
assert.equal(lineName('Spike in Errors (v4.9.4)', line52), 'Spike in Errors (v5.2.x)')
assert.equal(lineName('p50 Latency (Version 5.1.*)', line52), 'p50 Latency (Version 5.2.x)')
assert.equal(lineName('Correctness (Version 5.2.x)', line53), 'Correctness (Version 5.3.x)')
// Only whole three-part versions change.
assert.equal(lineName('cli', line52), 'cli')
assert.equal(lineName('p75 over 1.5s', line52), 'p75 over 1.5s')
assert.equal(lineName('build 10.2.0.1', line52), 'build 10.2.0.1')
})

test('raw SLI expressions match every version of the line with a regex', () => {
const expression =
'1 - (sum(rate(cli_commands_total{exit="unexpected_error", cli_version="5.2.0"} [15m])) / sum(rate(cli_commands_total{cli_version="5.2.0"} [15m])))'
const lined = lineExpression(expression, line52)
assert.equal(
lined,
'1 - (sum(rate(cli_commands_total{exit="unexpected_error", cli_version=~"5[.]2[.][0-9]+"} [15m])) / sum(rate(cli_commands_total{cli_version=~"5[.]2[.][0-9]+"} [15m])))',
)
assert.equal(lineExpression(lined, line52), lined)
assert.equal(lineExpression(lined, line53), lined.replaceAll('5[.]2[.]', '5[.]3[.]'))
// Other matchers stay as they are.
assert.equal(
lineExpression('sum(rate(cli_commands_total{exit!="ok"}[5m]))', line52),
'sum(rate(cli_commands_total{exit!="ok"}[5m]))',
)
assert.equal(lineExpression('vector(1)', line52), 'vector(1)')
})

test('histogram SLI filters match the line on cli_version and keep every other filter', () => {
const filters = [
{key: 'job', value: 'shopify-cli', op: '='},
{key: 'cli_version', value: '5.2.0', op: '='},
]
const lined = lineHistogramFilters(filters, line52)
assert.deepEqual(lined, [
{key: 'job', value: 'shopify-cli', op: '='},
{key: 'cli_version', value: '5[.]2[.][0-9]+', op: '=~'},
])
assert.deepEqual(lineHistogramFilters(lined, line53)[1], {key: 'cli_version', value: '5[.]3[.][0-9]+', op: '=~'})
})

// An SLI shaped like the CLI's correctness SLOs, with made-up values: the job matcher first in each selector, an
// error rate over a command rate, and a traffic guard that multiplies.
const correctness =
'1 - (sum(rate(cli_commands_total{job=~"@shopify/(app|store):.*", exit="error", cli_version="1.4.0"} [5m])) / sum(rate(cli_commands_total{job=~"@shopify/(app|store):.*", cli_version="1.4.0"} [5m]))) * on() (sum(rate(cli_commands_total{job=~"@shopify/(app|store):.*", cli_version="1.4.0"}[5m])) > 2)'
// Histogram filters shaped like the CLI's latency SLOs', with a made-up exclusion.
const latencyFilters = [
{key: 'job', value: 'excluded-command', op: '!='},
{key: 'job', value: '@shopify/(app|store):.*', op: '=~'},
{key: 'cli_version', value: '1.4.0', op: '='},
]

test('SLIs lose the job matcher and filter on traffic instead of multiplying by it', () => {
const lined = lineExpression(correctness, line52)
assert.equal(
lined,
'1 - (sum(rate(cli_commands_total{exit="error", cli_version=~"5[.]2[.][0-9]+"} [5m])) / sum(rate(cli_commands_total{cli_version=~"5[.]2[.][0-9]+"} [5m]))) and on() (sum(rate(cli_commands_total{cli_version=~"5[.]2[.][0-9]+"}[5m])) > 2)',
)
assert.equal(lineExpression(lined, line52), lined)
// A space before the guard's window doesn't matter.
const spaced = (expression) => expression.replace('}[5m])) > 2)', '} [5m])) > 2)')
assert.equal(lineExpression(spaced(correctness), line52), spaced(lined))
const linedFilters = lineHistogramFilters(latencyFilters, line52)
assert.deepEqual(linedFilters, [
{key: 'job', value: 'excluded-command', op: '!='},
{key: 'cli_version', value: '5[.]2[.][0-9]+', op: '=~'},
])
assert.deepEqual(lineHistogramFilters(linedFilters, line52), linedFilters)
})

/**
* A correctness SLI's value at one moment, given its two rates, under PromQL's rules for vectors of one sample: a
* comparison without `bool` keeps its left side's value or leaves no sample (NaN here), and `and on()` keeps its
* left side only while its right side has a sample.
*
* @param {string} expression
* @param {{errorsPerSecond: number, commandsPerSecond: number}} rates
* @returns {number}
*/
function correctnessAt(expression, {errorsPerSecond, commandsPerSecond}) {
const arithmetic = expression
.replace(/sum\(rate\(cli_commands_total\{[^}]*exit=[^}]*\}\s*\[\w+\]\)\)/g, `${errorsPerSecond}`)
.replace(/sum\(rate\(cli_commands_total\{[^}]*\}\s*\[\w+\]\)\)/g, `${commandsPerSecond}`)
.replace(/\(([\d.]+) > ([\d.]+)\)/g, (_comparison, left, right) =>
Number(left) > Number(right) ? `(${left})` : '(NaN)',
)
.replace(/\* on\(\)/g, '*')
const [value, guard] = arithmetic.split(' and on() ')
const evaluate = (code) => Function(`return ${code}`)()
return guard !== undefined && Number.isNaN(evaluate(guard)) ? NaN : evaluate(value)
}

test('a multiplied traffic guard makes a correctness SLI 1 minus errors a second, and the filter the error ratio', () => {
const busy = {errorsPerSecond: 0.002, commandsPerSecond: 300}
assert.ok(Math.abs(correctnessAt(correctness, busy) - (1 - 0.002)) < 1e-12)
assert.ok(Math.abs(correctnessAt(lineExpression(correctness, line52), busy) - (1 - 0.002 / 300)) < 1e-12)
// Below the guard's rate, both leave no sample.
const quiet = {errorsPerSecond: 0.01, commandsPerSecond: 1}
assert.ok(Number.isNaN(correctnessAt(correctness, quiet)))
assert.ok(Number.isNaN(correctnessAt(lineExpression(correctness, line52), quiet)))
})

test('only that job matcher goes, wherever it sits in a selector', () => {
const stale = 'job=~"@shopify/(app|store):.*"'
assert.equal(lineExpression(`m{exit="ok", ${stale}}`, line52), 'm{exit="ok"}')
assert.equal(
lineExpression(`m{exit="ok", ${stale}, cli_version="5.2.0"}`, line52),
'm{exit="ok", cli_version=~"5[.]2[.][0-9]+"}',
)
assert.equal(lineExpression(`m{${stale}}`, line52), 'm{}')
for (const kept of [
'job="cli"',
'job!="excluded-command"',
'job=~"@shopify/app:.*"',
'job!~"@shopify/(app|store):.*"',
]) {
assert.equal(lineExpression(`m{${kept}}`, line52), `m{${kept}}`)
}
const keptFilters = [
{key: 'job', value: '@shopify/(app|store):.*', op: '!~'},
{key: 'job', value: '@shopify/app:.*', op: '=~'},
{key: 'exit', value: '@shopify/(app|store):.*', op: '=~'},
]
assert.deepEqual(lineHistogramFilters(keptFilters, line52), keptFilters)
})

test('a traffic guard becomes a filter only where it multiplies by a cli_commands_total rate without bool', () => {
for (const kept of [
'x * on() (sum(rate(cli_commands_total{exit="ok"}[5m])) > bool 2)',
'x * on() (sum(rate(other_total{exit="ok"}[5m])) > 2)',
'x * on() (sum(rate(cli_commands_total{exit="ok"}[5m])))',
]) {
assert.equal(lineExpression(kept, line52), kept)
}
})

test('error filters start with the line, in every nested group, and keep everything else byte for byte', () => {
const filters =
'{"filters":null,"filter_groups":[{"filters":[{"column":"resource.service.name","op":"=","value":"cli"},{"column":"handled","op":"=","value":"false"},{"column":"app.version","op":"=","value":"5.2.0"}],"filter_groups":null,"conjunction":"AND"}],"conjunction":"AND"}'
const lined = lineErrorFilters(filters, 'app.version', line52)
assert.equal(
lined,
'{"filters":null,"filter_groups":[{"filters":[{"column":"resource.service.name","op":"=","value":"cli"},{"column":"handled","op":"=","value":"false"},{"column":"app.version","op":"starts-with","value":"5.2."}],"filter_groups":null,"conjunction":"AND"}],"conjunction":"AND"}',
)
assert.equal(lineErrorFilters(lined, 'app.version', line52), lined)
assert.equal(lineErrorFilters(lined, 'app.version', line53), lined.replace('"5.2."', '"5.3."'))
const nested =
'{"filters":[{"column":"app.version","op":"=","value":"5.1.0"}],"filter_groups":[{"filters":null,"filter_groups":[{"filters":[{"column":"app.version","op":"!=","value":"5.1.1"}],"filter_groups":null,"conjunction":"AND"}],"conjunction":"OR"}],"conjunction":"AND"}'
assert.equal(
lineErrorFilters(nested, 'app.version', line52),
'{"filters":[{"column":"app.version","op":"starts-with","value":"5.2."}],"filter_groups":[{"filters":null,"filter_groups":[{"filters":[{"column":"app.version","op":"!=","value":"5.1.1"}],"filter_groups":null,"conjunction":"AND"}],"conjunction":"OR"}],"conjunction":"AND"}',
)
})
Loading
Loading