diff --git a/.github/heavy-ci.md b/.github/heavy-ci.md
index 4b0d17bc3a3..e8b59d43190 100644
--- a/.github/heavy-ci.md
+++ b/.github/heavy-ci.md
@@ -5,7 +5,7 @@ action before expensive builds and tests. A failed, skipped, or cancelled
script-test job blocks those jobs, including manually dispatched runs. Each
workflow runs its own preflight so it does not wait on another workflow run.
-Rust CI keeps the Windows compilation check on PRs and merge groups. Windows
+Rust CI runs the Windows compilation check on its weekday schedule and on manual dispatch, not on PRs or merge groups. Windows
nextest and Windows SQLness run in the existing Nightly CI workflow, which also
supports manual dispatch. Its existing schedule is Tuesday through Friday at
07:00 Asia/Shanghai, not every day. No new Windows test job is added.
diff --git a/.github/nightly-merge.md b/.github/nightly-merge.md
index cc9419ec652..5f2f3552af0 100644
--- a/.github/nightly-merge.md
+++ b/.github/nightly-merge.md
@@ -1,18 +1,20 @@
# Nightly merge
-The PR template opts new PRs into the `merge nightly` label. The Nightly Merge
-workflow reconciles the label on PR creation, edits, and reopening. Existing PRs
-without the checkbox can opt in by adding the label manually; label sync leaves
-their labels unchanged. Unchecking removes the label; it does not
-request an immediate merge or cancel an existing queue entry/auto-merge request.
+Open PRs targeting `main` participate by default, including automated PRs
+without a checklist. Check **Skip nightly merge** to opt out. The scheduler
+honors the checkbox immediately, and label sync adds `skip nightly merge`.
+Uncheck the box to release the bot's hold. Maintainers can also apply the label
+directly and remove it when ready. If someone removes the label while the box
+is checked, label sync restores it. A manually applied label survives title
+and description edits.
Every day at 02:10, 03:10, 04:10, 05:10, 06:10, 07:10, and 08:10
Asia/Shanghai (UTC+8), the workflow enqueues up to five eligible PRs targeting
`main` per run, oldest first. Already queued PRs do not count toward this limit.
GitHub may delay scheduled runs.
-The label alone controls nightly opt-in; the enqueue job does not check the PR
-body. PRs must be approved and clean, and have all
-review threads resolved. Drafts are skipped.
+PRs must be approved and clean, with all review threads resolved. Drafts are
+skipped. The workflow rechecks the current opt-out label and checkbox before
+enqueueing at the reviewed head SHA.
If GitHub rejects enqueueing because a PR belongs to a stack, the workflow skips
it and continues without failing the run or counting it toward the five-PR limit.
Other API errors still fail the run. Dry runs do not call the enqueue API, so
@@ -23,7 +25,7 @@ scheduled run; this workflow never enables auto-merge on their behalf.
## Repository setup
-- Create the `merge nightly` label before enabling the workflow.
+- Create the `skip nightly merge` label before enabling the workflow.
- Require the merge queue, reviews, status checks, and conversation resolution
on `main`. Conversation resolution must also be enforced by GitHub to cover
new comments arriving between the script's check and enqueueing.
@@ -32,18 +34,70 @@ scheduled run; this workflow never enables auto-merge on their behalf.
branch-rule bypass. This credential is already referenced by other workflows;
its actual permissions have not been validated by the local tests.
- Run **Nightly Merge** manually with the default `dry_run: true` first and
- inspect its job summary. Setting it to false explicitly enqueues outside the
- scheduled time as well. Merge queue build concurrency is configured separately
- in GitHub; this workflow does not change it.
+ inspect its job summary. The repository variable `NIGHTLY_MERGE_ENABLED`
+ must be `true` for scheduled runs and manual dispatches that enqueue PRs.
+ Set it after completing the migration below.
-The workflow never checks out or executes PR code. Label reconciliation uses
-`GITHUB_TOKEN`; enqueueing uses the automation credential so downstream CI can
-run. No runner remains allocated while waiting for the nightly schedule.
+The PR event job reads the checklist helper from the trusted workflow commit.
+Label reconciliation uses `GITHUB_TOKEN`. Enqueueing uses the automation
+credential so downstream CI can run.
+
+## One-time migration of open PRs
+
+Use a maintainer's authenticated `gh` session from the checkout containing
+this change. PR body edits made by this account trigger checkbox label sync.
+
+1. Before merging, create the opt-out label. Leave `NIGHTLY_MERGE_ENABLED`
+ unset so the new workflow starts with enqueueing paused. Dry runs and label
+ sync remain available. Let any active enqueue job from the old workflow finish.
+2. Immediately after merging, capture the open PRs with their old labels.
+ Supply the rollout PR number so the snapshot excludes PRs opened at or
+ after GitHub's recorded merge time. New PRs can open throughout the rollout.
+ Finish or rerun any pending label updates from the old workflow before
+ taking the snapshot. Keep the file for verification and retries.
+
+ ```sh
+ node .github/scripts/migrate-pr-labels.cjs snapshot /tmp/pr-labels.json ROLLOUT_PR_NUMBER
+ ```
+
+3. Apply the saved snapshot. The migration removes `docs-not-required` from
+ captured open PRs on every base branch. For PRs targeting `main` both in
+ the snapshot and at apply time, it also converts legacy checkboxes and
+ removes `merge nightly`. A converted checkbox is unchecked if the PR had
+ `merge nightly` in the snapshot and checked otherwise. For PRs that lacked
+ the old label, `apply` adds a manual hold only when the checkbox is missing.
+ If an author unchecks **Skip nightly merge**, retrying `apply` honors that
+ choice. Coordinate retargeting and description edits during apply because
+ GitHub accepts the complete PR body on update.
+
+ ```sh
+ node .github/scripts/migrate-pr-labels.cjs apply /tmp/pr-labels.json
+ ```
+
+4. Let checkbox sync finish, then verify against the same snapshot. Verification
+ lists outstanding changes and exits unsuccessfully for any mismatch. If a
+ checked box still needs a label, rerun its failed label job or edit its
+ description to trigger sync. Confirm any new manual opt-out with the
+ maintainer and record it as an intentional difference. For a PR retargeted
+ into `main`, record its current choice with a **Skip nightly merge** checkbox
+ (checked to hold, unchecked to participate) or a manual `skip nightly merge`
+ label. Verification flags a retargeted PR until it has a current choice.
+ An interrupted apply can be rerun with the original snapshot.
+
+ ```sh
+ node .github/scripts/migrate-pr-labels.cjs verify /tmp/pr-labels.json
+ ```
+
+5. Run **Nightly Merge** with `dry_run: true` and inspect its summary. Once the
+ verified pool is correct, set `NIGHTLY_MERGE_ENABLED` to `true` to resume enqueueing.
+
+Docbot now adds `docs-required` when requested. On merge, that label controls
+whether it creates a follow-up issue in the docs repository.
## Local validation
-Run `actionlint .github/workflows/nightly-merge.yml .github/workflows/checks.yml`
-and `node --test .github/scripts/tests/nightly-merge.test.cjs`.
-The tests execute the actual inline workflow scripts with mocked GitHub APIs,
+Run `actionlint .github/workflows/{nightly-merge,docbot,checks}.yml`,
+`node --test .github/scripts/tests/nightly-merge.test.cjs`, and `pnpm --dir cyborg test`.
+The tests execute the workflow scripts with mocked GitHub APIs,
including one-factor comparisons against an eligible PR. They do not validate
live GitHub permissions, branch rules, or runner savings.
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
index 5b26f64ceb3..2e797c41a33 100644
--- a/.github/pull_request_template.md
+++ b/.github/pull_request_template.md
@@ -28,11 +28,11 @@ Please convert it to a draft if some of the following conditions are not met.
## Merge timing
-- [x] Merge during the nightly window
+- [ ] Skip nightly merge
diff --git a/.github/scripts/migrate-pr-labels.cjs b/.github/scripts/migrate-pr-labels.cjs
new file mode 100644
index 00000000000..9c4f6a28536
--- /dev/null
+++ b/.github/scripts/migrate-pr-labels.cjs
@@ -0,0 +1,126 @@
+// Copyright 2023 Greptime Team
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+const { execFileSync } = require('node:child_process');
+const { readFileSync, writeFileSync } = require('node:fs');
+const { checklistItems, skipCheckboxState, skipLabel } = require('./nightly-merge.cjs');
+
+const repository = 'GreptimeTeam/greptimedb';
+const oldNightly = 'merge nightly';
+const oldDocs = 'docs-not-required';
+
+function api(path, args = [], data) {
+ const input = data === undefined ? undefined : JSON.stringify(data);
+ return execFileSync('gh', ['api', `repos/${repository}/${path}`, ...args,
+ ...(input === undefined ? [] : ['--input', '-'])], { encoding: 'utf8', input });
+}
+
+function migrateBody(body, hold) {
+ let updated = body;
+ // Work backwards so each replacement keeps the offsets of earlier items valid.
+ for (const item of [...checklistItems(body)].reverse()) {
+ const old = /^Merge during the nightly window\b(?:[ \t]*)?/i.exec(item.text);
+ if (old) {
+ const following = updated.slice(item.end).replace(/^(?:[ \t]*\r?\n)+ {0,3}/, comment =>
+ comment.replace(/^Uncheck to opt out and remove the `merge nightly` label; this does not enable immediate merging\.$/m,
+ 'Check to opt out. To resume, uncheck the box and remove any manually applied `skip nightly merge` label.'));
+ updated = updated.slice(0, item.index) + (hold ? '[x]' : '[ ]') + item.space +
+ 'Skip nightly merge' + item.text.slice(old[0].length) + following;
+ }
+ }
+ return updated;
+}
+
+function changesFor(entry, pr) {
+ const labels = new Set(pr.labels.map(label => label.name));
+ const targetsMain = pr.base.ref === 'main';
+ const migrateNightly = targetsMain && entry.base === 'main';
+ const hold = migrateNightly && !entry.optedIn;
+ const body = migrateNightly ? migrateBody(pr.body, hold) : pr.body;
+ const checkbox = targetsMain ? skipCheckboxState(body) : null;
+ const labeled = labels.has(skipLabel);
+ const obsolete = migrateNightly ? [oldNightly, oldDocs] : [oldDocs];
+ return {
+ body,
+ // A converted checked box gets a bot-owned label from its edit event.
+ addHold: hold && checkbox === null && !labeled,
+ remove: obsolete.filter(label => labels.has(label)),
+ waitingForSync: checkbox === true && !labeled,
+ extraHold: migrateNightly && entry.optedIn && (checkbox === true || labeled),
+ needsChoice: targetsMain && !migrateNightly && checkbox === null && !labeled,
+ };
+}
+
+function openBefore(mergedAt) {
+ const rows = api('pulls?state=open&sort=created&direction=asc&per_page=100', ['--paginate', '--jq',
+ `.[] | select(.created_at < ${JSON.stringify(mergedAt)}) | {number, base: .base.ref, optedIn: any(.labels[]; .name == "${oldNightly}")} | @json`]);
+ return rows.trim().split('\n').filter(Boolean).map(line => JSON.parse(line));
+}
+
+function main([mode, file, rolloutPR]) {
+ if (!file || !['snapshot', 'apply', 'verify'].includes(mode) || (mode === 'snapshot' && !/^[1-9]\d*$/.test(rolloutPR))) {
+ throw new Error('Usage: node .github/scripts/migrate-pr-labels.cjs snapshot SNAPSHOT.json ROLLOUT_PR | apply|verify SNAPSHOT.json');
+ }
+ if (mode === 'snapshot') {
+ const { merged_at: mergedAt, base } = JSON.parse(api(`pulls/${rolloutPR}`));
+ if (!mergedAt || base.ref !== 'main') throw new Error(`Rollout PR #${rolloutPR} must be merged into main`);
+ const prs = openBefore(mergedAt);
+ writeFileSync(file, JSON.stringify({ repository, rolloutPR, mergedAt, prs }, null, 2) + '\n', { flag: 'wx' });
+ console.log(`Saved ${prs.length} open PRs to ${file}`);
+ return;
+ }
+ const snapshot = JSON.parse(readFileSync(file, 'utf8'));
+ if (snapshot.repository !== repository || !snapshot.mergedAt || !Array.isArray(snapshot.prs) || !snapshot.prs.every(entry =>
+ Number.isSafeInteger(entry.number) && entry.number > 0 && typeof entry.base === 'string' && typeof entry.optedIn === 'boolean')) {
+ throw new Error('Invalid migration snapshot');
+ }
+ let open = 0;
+ if (mode === 'verify') {
+ const captured = new Set(snapshot.prs.map(entry => entry.number));
+ for (const pr of openBefore(snapshot.mergedAt)) {
+ if (!captured.has(pr.number)) {
+ console.error(`#${pr.number}: open before rollout but missing from the snapshot`);
+ process.exitCode = 1;
+ }
+ }
+ }
+ for (const entry of snapshot.prs) {
+ const number = entry.number;
+ const pr = JSON.parse(api(`pulls/${number}`));
+ if (pr.state !== 'open') continue;
+ open++;
+ const { body, addHold, remove, waitingForSync, extraHold, needsChoice } = changesFor(entry, pr);
+ if (mode === 'apply') {
+ if (body !== pr.body) api(`pulls/${number}`, ['--method', 'PATCH', '--silent'], { body });
+ if (addHold) api(`issues/${number}/labels`, ['--method', 'POST', '--silent'], { labels: [skipLabel] });
+ for (const label of remove) {
+ api(`issues/${number}/labels/${encodeURIComponent(label)}`, ['--method', 'DELETE', '--silent']);
+ }
+ } else {
+ const pending = remove.map(label => `remove ${label}`);
+ if (body !== pr.body) pending.push('convert legacy checkbox');
+ if (addHold || waitingForSync) pending.push(`missing ${skipLabel}`);
+ if (extraHold) pending.push('review opt-out added since snapshot');
+ if (needsChoice) pending.push(`record a nightly preference after retargeting from ${entry.base} to main`);
+ if (pending.length) {
+ console.error(`#${number}: ${pending.join(', ')}`);
+ process.exitCode = 1;
+ }
+ }
+ }
+ console.log(`${mode === 'apply' ? 'Applied migration to' : 'Checked'} ${open} open PRs from ${file}`);
+}
+
+if (require.main === module) main(process.argv.slice(2));
+module.exports = { changesFor };
diff --git a/.github/scripts/nightly-merge.cjs b/.github/scripts/nightly-merge.cjs
new file mode 100644
index 00000000000..9fba4be3aa8
--- /dev/null
+++ b/.github/scripts/nightly-merge.cjs
@@ -0,0 +1,79 @@
+// Copyright 2023 Greptime Team
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+const skipLabel = 'skip nightly merge';
+
+// Exclude quoted, commented and fenced examples from both sync and migration.
+function* checklistItems(body) {
+ let fence = '';
+ let inComment = false;
+ const listIndents = [0];
+ for (const match of (body || '').matchAll(/^[^\r\n]+/gm)) {
+ const line = match[0];
+ if (!line.trim()) continue;
+ const block = line.includes('\t') ? line.split('\t').reduce((before, after) =>
+ before + ' '.repeat(4 - before.length % 4) + after) : line;
+ const indent = /^ */.exec(block)[0].length;
+ // Leaving a list item also ends its fence, even without a closing delimiter.
+ while (indent < listIndents.at(-1)) {
+ listIndents.pop();
+ fence = '';
+ }
+ let content = block.slice(listIndents.at(-1));
+ if (!fence && !inComment) {
+ let list;
+ while ((list = /^ {0,3}(?:[-*+]|\d{1,9}[.)]) {1,4}(?=\S)/.exec(content))) {
+ listIndents.push(listIndents.at(-1) + list[0].length);
+ content = content.slice(list[0].length);
+ }
+ }
+ const marker = /^ {0,3}(`{3,}(?=[^`]*$)|~{3,})/.exec(content)?.[1];
+ if (fence) {
+ if (marker?.startsWith(fence) && content.trim() === marker) fence = '';
+ } else if (inComment) {
+ inComment = !line.includes('-->');
+ } else if (marker) {
+ fence = marker;
+ } else {
+ inComment = line.trimStart().startsWith('');
+ const item = /^( {0,3}[-*+][ \t]+)\[([ xX])\]([ \t]+)(.*)$/.exec(line);
+ if (item) {
+ yield { index: match.index + item[1].length, end: match.index + line.length,
+ checked: item[2] !== ' ', space: item[3], text: item[4] };
+ }
+ }
+ }
+}
+
+// Rollout verification distinguishes a missing checkbox from an unchecked one.
+function skipCheckboxState(body) {
+ let state = null;
+ for (const item of checklistItems(body)) {
+ if (!/^Skip nightly merge\b/i.test(item.text)) continue;
+ if (item.checked) return true;
+ state = false;
+ }
+ return state;
+}
+
+function skipChecked(body) {
+ return skipCheckboxState(body) === true;
+}
+
+function eligibleForNightly(pr) {
+ return pr.state === 'open' && !pr.draft && pr.base.ref === 'main' &&
+ !pr.labels.some(label => label.name === skipLabel) && !skipChecked(pr.body);
+}
+
+module.exports = { checklistItems, skipLabel, skipCheckboxState, skipChecked, eligibleForNightly };
diff --git a/.github/scripts/tests/nightly-merge.test.cjs b/.github/scripts/tests/nightly-merge.test.cjs
index d6c8792f7fe..de6d13ccb03 100644
--- a/.github/scripts/tests/nightly-merge.test.cjs
+++ b/.github/scripts/tests/nightly-merge.test.cjs
@@ -19,27 +19,48 @@ const assert = require('node:assert/strict');
const { test } = require('node:test');
const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor;
const workflow = readFileSync(resolve(__dirname, '../../workflows/nightly-merge.yml'), 'utf8');
+const template = readFileSync(resolve(__dirname, '../../pull_request_template.md'), 'utf8');
const scripts = [...workflow.matchAll(/ script: \|\n((?: .*\n|\n)+)/g)]
- .map(match => new AsyncFunction('github', 'context', 'core', 'process', match[1].replace(/^ /gm, '')));
+ .map(match => new AsyncFunction('github', 'context', 'core', 'process', 'require', match[1].replace(/^ /gm, '')));
assert.equal(scripts.length, 2);
-const checked = '- [x] Merge during the nightly window ';
+const { changesFor } = require('../migrate-pr-labels.cjs');
+const label = 'skip nightly merge';
+const checked = '- [x] Skip nightly merge';
+const unchecked = '- [ ] Skip nightly merge';
+const legacy = '- [x] Merge during the nightly window ';
-async function run({ sync = false, body = checked, labels = ['merge nightly'],
- detail = {}, current = {}, threads = [[true]], count = 1, dryRun = false,
+function migrateMainPr(optedIn, pr) {
+ return changesFor({ base: 'main', optedIn }, { ...pr, base: { ref: 'main' } });
+}
+
+async function run({ sync = false, body = unchecked, labels = [], events = [], payload = {},
+ detail = {}, listed = {}, current = {}, threads = [[true]], count = 1, dryRun = false,
failFirst = false, enqueueError = Error('head changed') } = {}) {
const calls = [];
let page = 0;
+ const pr = { state: 'open', draft: false, base: { ref: 'main' }, body, labels: labels.map(name => ({ name })) };
const github = {
rest: {
- pulls: { get: async () => ({ data: { state: 'open', draft: false, base: { ref: 'main' },
- body, labels: labels.map(name => ({ name })), ...current } }) },
+ pulls: { list() {}, get: async () => {
+ if (!sync) calls.push(['get']);
+ return { data: { ...pr, ...current } };
+ } },
issues: {
- listForRepo: () => {},
+ listEvents() {},
addLabels: async args => calls.push(['add', args.labels]),
removeLabel: async args => calls.push(['remove', args.name])
}
},
- paginate: async () => Array.from({ length: count }, (_, i) => ({ number: i + 1, pull_request: {} })),
+ paginate: async (route, args) => {
+ if (route === github.rest.issues.listEvents) {
+ assert.equal(args.issue_number, 1);
+ return events;
+ }
+ assert.equal(route, github.rest.pulls.list);
+ assert.deepEqual(args, { owner: 'GreptimeTeam', repo: 'greptimedb', state: 'open', base: 'main',
+ sort: 'created', direction: 'asc', per_page: 100 });
+ return Array.from({ length: count }, (_, i) => ({ ...pr, number: i + 1, ...listed }));
+ },
graphql: async (query, args) => {
if (query.includes('mutation')) {
calls.push(['enqueue', args]);
@@ -60,26 +81,77 @@ async function run({ sync = false, body = checked, labels = ['merge nightly'],
};
const summary = { addHeading() { return this; }, addTable(rows) { calls.push(['summary', rows]); return this; }, async write() {} };
await scripts[sync ? 0 : 1](github,
- { repo: { owner: 'GreptimeTeam', repo: 'greptimedb' }, payload: { pull_request: { number: 1 } } },
+ { repo: { owner: 'GreptimeTeam', repo: 'greptimedb' }, payload: { pull_request: { number: 1 }, ...payload } },
{ summary, info() {}, warning() {}, setFailed: message => calls.push(['failed', message]) },
- { env: { DRY_RUN: String(dryRun) } });
+ { env: { DRY_RUN: String(dryRun) } }, path => require(resolve(__dirname, '../../..', path)));
return calls;
}
-test('label sync grants PR label write permission without checking out PR code', () => {
+test('label sync reads the helper from the trusted workflow commit', () => {
const syncJob = workflow.split(' sync-label:\n')[1].split(' enqueue:\n')[0];
assert.match(syncJob, /^ pull-requests: write$/m);
- assert.doesNotMatch(syncJob, /uses: actions\/checkout/);
+ assert.match(syncJob, /ref: \$\{\{ github\.sha \}\}/);
+ assert.match(syncJob, /persist-credentials: false/);
+ assert.doesNotMatch(syncJob, /pull_request\.head/);
});
-test('template opts in and checkbox edits reconcile only the nightly label', async () => {
- assert.ok(readFileSync(resolve(__dirname, '../../pull_request_template.md'), 'utf8').includes(checked));
- assert.deepEqual(await run({ sync: true, labels: ['bug'] }), [['add', ['merge nightly']]]);
+test('removing the skip label reconciles the current checkbox on main', async () => {
+ const trigger = workflow.split(' pull_request_target:\n')[1].split(' schedule:\n')[0];
+ assert.match(trigger, /branches: \[main\]/);
+ assert.match(trigger, /types: \[[^\]\n]*\bunlabeled\b/);
+ const guard = workflow.split(' sync-label:\n')[1].match(/ if: >-\n((?: .*\n)+)/)[1];
+ const enabled = new Function('github', `return (${guard});`);
+ const payload = { action: 'unlabeled', label: { name: label } };
+ const admits = event => enabled({ repository: 'GreptimeTeam/greptimedb', event_name: 'pull_request_target', event });
+ assert.equal(admits(payload), true);
+ assert.equal(admits({ ...payload, label: { name: 'docs-required' } }), false);
+ assert.equal(admits({ action: 'edited' }), true);
+
+ const opts = { sync: true, payload };
+ assert.deepEqual(await run({ ...opts, body: checked }), [['add', [label]]]);
+ for (const body of [unchecked, null]) assert.deepEqual(await run({ ...opts, body }), []);
+ assert.deepEqual(await run({ ...opts, body: checked, current: { base: { ref: 'release/v1.3' } } }), []);
+});
+
+test('enqueueing requires rollout activation and dry runs work while paused', () => {
+ const guard = workflow.split(' enqueue:\n')[1].match(/ if: >-\n((?: .*\n)+)/)[1];
+ const enabled = new Function('github', 'vars', 'inputs', `return (${guard});`);
+ const repo = { repository: 'GreptimeTeam/greptimedb' };
+ for (const flag of ['', 'false', 'true']) {
+ const vars = { NIGHTLY_MERGE_ENABLED: flag };
+ const scheduled = { ...repo, event_name: 'schedule' };
+ const manual = { ...repo, event_name: 'workflow_dispatch' };
+ assert.equal(enabled(scheduled, vars, {}), flag === 'true');
+ assert.equal(enabled(manual, vars, { dry_run: false }), flag === 'true');
+ assert.equal(enabled(manual, vars, { dry_run: true }), true);
+ assert.equal(enabled({ ...repo, event_name: 'pull_request_target' }, vars, {}), false);
+ }
+});
+
+test('default template needs no label and a checked opt-out is effective before sync', async () => {
+ assert.ok(template.includes(unchecked));
+ assert.deepEqual(await run({ sync: true, body: template }), []);
+ for (const body of [checked, checked.replace('[x]', '[X]') + ' — wait for backport',
+ checked + ' more details', unchecked + '\r\n' + checked]) {
+ assert.deepEqual(await run({ sync: true, body, labels: ['bug'] }), [['add', [label]]]);
+ assert.equal((await run({ body })).some(c => c[0] === 'enqueue'), false);
+ }
assert.deepEqual(await run({ sync: true }), []);
- for (const body of [checked.replace('[x]', '[ ]')]) {
- assert.deepEqual(await run({ sync: true, body }), [['remove', 'merge nightly']]);
+ assert.deepEqual(await run({ sync: true, body: checked, labels: [label] }), []);
+});
+
+test('a coalesced uncheck releases a bot hold; delayed edits and reopens preserve a newer manual hold', async () => {
+ const bot = { id: 1, created_at: '2026-01-01T00:00:00Z', event: 'labeled', label: { name: label },
+ actor: { login: 'github-actions[bot]' } };
+ const removed = { ...bot, id: 2, event: 'unlabeled' };
+ const manual = { ...bot, id: 3, actor: { login: 'maintainer' } };
+ for (const payload of [{ action: 'edited', changes: { title: { from: 'before' } } },
+ { action: 'edited', changes: { body: { from: checked } } }, { action: 'reopened' }]) {
+ const opts = { sync: true, labels: [label], payload };
+ assert.deepEqual(await run({ ...opts, events: [bot] }), [['remove', label]]);
+ assert.deepEqual(await run({ ...opts, events: [manual, bot, removed] }), []);
+ assert.deepEqual(await run({ ...opts, events: [] }), []);
}
- assert.deepEqual(await run({ sync: true, body: checked.replace('[x]', '[X]'), labels: [] }), [['add', ['merge nightly']]]);
});
test('eligible PR is enqueued with its checked head; dry run performs no mutation', async () => {
@@ -89,7 +161,8 @@ test('eligible PR is enqueued with its checked head; dry run performs no mutatio
test('each eligibility gate independently prevents enqueueing', async () => {
for (const options of [
- { labels: [] },
+ { labels: [label] }, { listed: { draft: true } }, { current: { labels: [{ name: label }] } },
+ { current: { body: checked } },
{ current: { draft: true } }, { current: { state: 'closed' } }, { current: { base: { ref: 'release/v1.3' } } },
{ detail: { reviewDecision: 'REVIEW_REQUIRED' } }, { detail: { reviewDecision: 'CHANGES_REQUESTED' } },
{ detail: { mergeStateStatus: 'BLOCKED' } }, { detail: { mergeStateStatus: 'UNKNOWN' } },
@@ -103,6 +176,7 @@ test('each eligibility gate independently prevents enqueueing', async () => {
test('all thread pages are checked before enqueueing', async () => {
const calls = await run({ threads: [[true], [true]] });
assert.deepEqual(calls.filter(c => c[0] === 'threads'), [['threads', null], ['threads', 'page-0']]);
+ assert.ok(calls.findIndex(c => c[0] === 'get') > calls.findLastIndex(c => c[0] === 'threads'));
assert.equal(calls.filter(c => c[0] === 'enqueue').length, 1);
});
@@ -113,15 +187,110 @@ test('per-run cap and individual failures do not prevent later candidates', asyn
assert.equal(calls.filter(c => c[0] === 'failed').length, 1);
});
-test('label-only opt-in survives PRs without a template and does not require a checkbox', async () => {
- for (const body of ['', null, 'Existing PR description', `> ${checked}`]) {
+test('checkbox-free PRs enter by default and manual holds work on any description', async () => {
+ for (const body of ['', null, 'Automated PR', `> ${checked}`, `\`\`\`md\n${checked}\n\`\`\``,
+ ``, legacy, legacy.replace('[x]', '[ ]')]) {
assert.deepEqual(await run({ sync: true, body }), []);
- assert.deepEqual(await run({ sync: true, body, labels: [] }), []);
assert.equal((await run({ body })).filter(call => call[0] === 'enqueue').length, 1);
- assert.equal((await run({ body, labels: [] })).some(call => call[0] === 'enqueue'), false);
+ assert.equal((await run({ body, labels: [label] })).some(call => call[0] === 'enqueue'), false);
}
- // The label is authoritative for admission, even before checkbox synchronization.
- assert.equal((await run({ body: checked.replace('[x]', '[ ]') })).some(call => call[0] === 'enqueue'), true);
+});
+
+test('list fences hide example checkboxes and leave the following merge checklist effective', async () => {
+ for (const [opening, indent, closing] of [
+ ['1. ```sql', ' ', ' ```'],
+ ['10) ~~~md', ' ', ' ~~~~'],
+ ['- ```md', ' ', ''],
+ ['1.\t```md', ' ', '\t```'],
+ ['1. Reproduction\n ```md', ' ', '']
+ ]) {
+ const description = (sample, box) =>
+ [opening, indent + 'SELECT 1;', '', indent + sample, closing, '', '## Merge timing', '', box].join('\n');
+ for (const [sample, box] of [[unchecked, checked], [checked, unchecked]]) {
+ const body = description(sample, box);
+ assert.deepEqual(await run({ sync: true, body }), box === checked ? [['add', [label]]] : [], body);
+ assert.equal((await run({ body })).some(call => call[0] === 'enqueue'), box === unchecked, body);
+ }
+ assert.equal(migrateMainPr(false, { body: description(legacy, legacy), labels: [] }).body,
+ description(legacy, checked));
+ }
+});
+
+test('migration follows the snapshotted label, edits only visible legacy items and preserves docs overrides', () => {
+ for (const optedIn of [false, true]) {
+ const old = '- [ ] Merge during the nightly window';
+ const before = ['Author notes', `> ${old}`, '```md', old, '```', '', ''];
+ const pr = { body: [...before, old + ' — note', legacy + ' (later)'].join('\r\n'),
+ labels: ['docs-required', 'bug', 'docs-not-required', ...(optedIn ? ['merge nightly'] : [])].map(name => ({ name })) };
+ const result = migrateMainPr(optedIn, pr);
+ const replacement = optedIn ? unchecked : checked;
+ assert.equal(result.body, [...before, replacement + ' — note', replacement + ' (later)'].join('\r\n'));
+ assert.deepEqual(result.remove, optedIn ? ['merge nightly', 'docs-not-required'] : ['docs-not-required']);
+ assert.equal(result.addHold, false);
+ assert.equal(result.waitingForSync, !optedIn);
+ const migrated = { body: result.body, labels: optedIn ? [] : [{ name: label }] };
+ assert.deepEqual(migrateMainPr(optedIn, migrated), { body: migrated.body, addHold: false, remove: [],
+ waitingForSync: false, extraHold: false, needsChoice: false });
+ }
+});
+
+test('retrying migration honors a cleared nightly opt-out checkbox', () => {
+ const retry = migrateMainPr(false, { body: unchecked, labels: [] });
+ assert.deepEqual(retry, { body: unchecked, addHold: false, remove: [],
+ waitingForSync: false, extraHold: false, needsChoice: false });
+});
+
+test('migration only cleans the old docs label on release PRs, including PRs retargeted from main', () => {
+ const release = 'release/v1.3';
+ for (const [base, optedIn] of [[release, true], ['main', false]]) {
+ const names = ['docs-required', 'docs-not-required', ...(optedIn ? ['merge nightly'] : [])];
+ for (const body of [legacy, null, checked]) {
+ const pr = { base: { ref: release }, body, labels: names.map(name => ({ name })) };
+ assert.deepEqual(changesFor({ base, optedIn }, pr), { body, addHold: false, remove: ['docs-not-required'],
+ waitingForSync: false, extraHold: false, needsChoice: false });
+ }
+ }
+});
+
+test('a PR retargeted into main needs a current checkbox or manual hold', () => {
+ const entry = { base: 'release/v1.3', optedIn: true };
+ for (const [body, names, needsChoice, waitingForSync] of [
+ [legacy, ['merge nightly'], true, false], [null, [], true, false],
+ ['> ' + unchecked, [], true, false], [unchecked, [], false, false],
+ [checked, [], false, true], [null, [label], false, false]
+ ]) {
+ const pr = { base: { ref: 'main' }, body, labels: names.map(name => ({ name })) };
+ assert.deepEqual(changesFor(entry, pr), { body, addHold: false, remove: [],
+ waitingForSync, extraHold: false, needsChoice });
+ }
+});
+
+test('migration updates the stock help only in the comment following a converted checkbox', () => {
+ const oldHelp = 'Uncheck to opt out and remove the `merge nightly` label; this does not enable immediate merging.';
+ const newHelp = 'Check to opt out. To resume, uncheck the box and remove any manually applied `skip nightly merge` label.';
+ const migrate = (body, optedIn) => migrateMainPr(optedIn, { body, labels: [] }).body;
+ assert.ok(template.includes(newHelp));
+ assert.equal(migrate(template.replace(unchecked, legacy).replace(newHelp, oldHelp), true), template);
+
+ const description = (box, help) => [
+ oldHelp, '', '```md', legacy, '', '```', '',
+ box + ' — waiting for a backport', '', '', '',
+ ''
+ ].join('\r\n');
+ assert.equal(migrate(description(legacy, oldHelp), false), description(checked, newHelp));
+ assert.equal(migrate(description(legacy, oldHelp + ' Custom note.'), false),
+ description(checked, oldHelp + ' Custom note.'));
+ assert.equal(migrate(description(checked, oldHelp), false), description(checked, oldHelp));
+});
+
+test('migration holds checkbox-free PRs across retries and flags a later manual opt-out for review', () => {
+ const pr = { body: null, labels: [] };
+ assert.equal(migrateMainPr(false, pr).addHold, true);
+ assert.equal(migrateMainPr(true, pr).addHold, false);
+ pr.labels.push({ name: label });
+ assert.equal(migrateMainPr(false, pr).addHold, false);
+ assert.equal(migrateMainPr(true, pr).extraHold, true);
+ assert.equal(migrateMainPr(false, pr).body, null);
});
const stackMessage = 'This pull request is part of a stack and must be enqueued using the asynchronous merge REST API. For more information, see https://docs.github.com/rest/pulls/pulls#merge-a-pull-request-asynchronously';
diff --git a/.github/workflows/docbot.yml b/.github/workflows/docbot.yml
index 53033c6eb5b..1576dd7a454 100644
--- a/.github/workflows/docbot.yml
+++ b/.github/workflows/docbot.yml
@@ -3,12 +3,17 @@ on:
pull_request_target:
types: [opened, edited, closed]
-concurrency:
- group: ${{ github.workflow }}-${{ github.event.action }}-${{ github.head_ref || github.run_id }}
- cancel-in-progress: true
-
jobs:
docbot:
+ # An unrelated edit must not displace a pending docs checkbox change.
+ if: >-
+ github.event.action != 'edited' ||
+ (github.event.changes.body &&
+ contains(github.event.changes.body.from, '[x] This PR requires documentation updates.') !=
+ contains(github.event.pull_request.body, '[x] This PR requires documentation updates.'))
+ concurrency:
+ group: ${{ github.workflow }}-${{ github.event.pull_request.number }}-${{ github.event.action == 'closed' && 'close' || 'labels' }}
+ cancel-in-progress: false
runs-on: ubuntu-latest
permissions:
pull-requests: write
diff --git a/.github/workflows/nightly-merge.yml b/.github/workflows/nightly-merge.yml
index 05f5154358b..d4142b03f97 100644
--- a/.github/workflows/nightly-merge.yml
+++ b/.github/workflows/nightly-merge.yml
@@ -3,7 +3,8 @@ name: Nightly Merge
on:
pull_request_target:
- types: [opened, edited, reopened]
+ branches: [main]
+ types: [opened, edited, reopened, unlabeled]
schedule:
# Hourly from 02:10 through 08:10 Asia/Shanghai (UTC+8), inclusive.
# GitHub may delay scheduled runs.
@@ -19,44 +20,68 @@ permissions: {}
jobs:
sync-label:
- if: github.repository == 'GreptimeTeam/greptimedb' && github.event_name == 'pull_request_target'
+ if: >-
+ github.repository == 'GreptimeTeam/greptimedb' && github.event_name == 'pull_request_target' &&
+ (github.event.action != 'unlabeled' || github.event.label.name == 'skip nightly merge')
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
- # PR label mutations require pull-request write permission.
+ contents: read
pull-requests: write
issues: write
concurrency:
group: nightly-merge-label-${{ github.event.pull_request.number }}
cancel-in-progress: false
steps:
- # No checkout: PR contents are untrusted data, never executable code.
+ # On pull_request_target github.sha identifies trusted base-repository code.
+ - uses: actions/checkout@v4
+ with:
+ ref: ${{ github.sha }}
+ sparse-checkout: .github/scripts/nightly-merge.cjs
+ sparse-checkout-cone-mode: false
+ persist-credentials: false
- uses: actions/github-script@v7
with:
script: |
+ const { skipChecked, skipLabel } = require('./.github/scripts/nightly-merge.cjs');
const { owner, repo } = context.repo;
const issue_number = context.payload.pull_request.number;
const { data: pr } = await github.rest.pulls.get({ owner, repo, pull_number: issue_number });
- const checkbox = /^- \[([ xX])\] Merge during the nightly window \s*$/m.exec(pr.body || '');
- // PRs without the template manage their opt-in through the label.
- if (!checkbox) return;
- const selected = checkbox[1].toLowerCase() === 'x';
- const label = 'merge nightly';
- const labeled = pr.labels.some(item => item.name === label);
- if (selected && !labeled) {
- await github.rest.issues.addLabels({ owner, repo, issue_number, labels: [label] });
- } else if (!selected && labeled) {
- await github.rest.issues.removeLabel({ owner, repo, issue_number, name: label });
+ if (pr.state !== 'open' || pr.base.ref !== 'main') return;
+ const selected = skipChecked(pr.body);
+ const labeled = pr.labels.some(item => item.name === skipLabel);
+ if (selected === labeled) return;
+ if (selected) {
+ await github.rest.issues.addLabels({ owner, repo, issue_number, labels: [skipLabel] });
+ } else {
+ // Only undo the bot's own label. A maintainer may have applied a hold since the edit.
+ const events = await github.paginate(github.rest.issues.listEvents, { owner, repo, issue_number, per_page: 100 });
+ const [last] = events.filter(event => event.label?.name === skipLabel &&
+ (event.event === 'labeled' || event.event === 'unlabeled'))
+ .sort((a, b) => b.created_at.localeCompare(a.created_at) || b.id - a.id);
+ if (last?.event === 'labeled' && last.actor?.login === 'github-actions[bot]') {
+ await github.rest.issues.removeLabel({ owner, repo, issue_number, name: skipLabel });
+ }
}
enqueue:
- if: github.repository == 'GreptimeTeam/greptimedb' && github.event_name != 'pull_request_target'
+ if: >-
+ github.repository == 'GreptimeTeam/greptimedb' && github.event_name != 'pull_request_target' &&
+ (vars.NIGHTLY_MERGE_ENABLED == 'true' || (github.event_name == 'workflow_dispatch' && inputs.dry_run))
runs-on: ubuntu-latest
timeout-minutes: 10
+ permissions:
+ contents: read
concurrency:
group: nightly-merge-enqueue
cancel-in-progress: false
steps:
+ - uses: actions/checkout@v4
+ with:
+ ref: ${{ github.sha }}
+ sparse-checkout: .github/scripts/nightly-merge.cjs
+ sparse-checkout-cone-mode: false
+ persist-credentials: false
# Reuses the automation credential used by backport and compat updates.
# A PAT (or App token) lets subsequent merge_group workflows run.
- uses: actions/github-script@v7
@@ -65,25 +90,20 @@ jobs:
with:
github-token: ${{ secrets.GH_PERSONAL_ACCESS_TOKEN }}
script: |
+ const { eligibleForNightly } = require('./.github/scripts/nightly-merge.cjs');
const { owner, repo } = context.repo;
const dryRun = process.env.DRY_RUN === 'true';
- const candidates = await github.paginate(github.rest.issues.listForRepo, {
- owner, repo, state: 'open', labels: 'merge nightly',
+ const candidates = await github.paginate(github.rest.pulls.list, {
+ owner, repo, state: 'open', base: 'main',
sort: 'created', direction: 'asc', per_page: 100
});
const rows = [];
let enqueued = 0;
for (const candidate of candidates) {
- if (!candidate.pull_request || enqueued >= 5) continue;
+ if (enqueued >= 5) break;
+ if (!eligibleForNightly(candidate)) continue;
const number = candidate.number;
try {
- // Fetch current labels and PR state, not the earlier list snapshot.
- const { data: current } = await github.rest.pulls.get({ owner, repo, pull_number: number });
- if (current.state !== 'open' || current.draft || current.base.ref !== 'main' ||
- !current.labels.some(label => label.name === 'merge nightly')) {
- rows.push([String(number), 'Skipped: not opted in, draft, closed, or not targeting main']);
- continue;
- }
const { repository: { pullRequest: pr } } = await github.graphql(`
query($owner: String!, $repo: String!, $number: Int!) {
repository(owner: $owner, name: $repo) {
@@ -120,6 +140,12 @@ jobs:
rows.push([String(number), 'Skipped: unresolved review threads']);
continue;
}
+ // An opt-out may have arrived while checking reviews and threads.
+ const { data: current } = await github.rest.pulls.get({ owner, repo, pull_number: number });
+ if (!eligibleForNightly(current)) {
+ rows.push([String(number), 'Skipped: opted out, draft, closed, or not targeting main']);
+ continue;
+ }
if (!dryRun) {
// GitHub enforces branch rules; never bypass or enable auto-merge.
try {
diff --git a/Cargo.lock b/Cargo.lock
index a1759e00ab6..acdc39ea8cd 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2958,7 +2958,6 @@ dependencies = [
"serde_json",
"snafu 0.8.6",
"tempfile",
- "tokio",
"tracing",
"tracing-appender",
"tracing-log",
@@ -5625,9 +5624,9 @@ checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
[[package]]
name = "form_urlencoded"
-version = "1.2.2"
+version = "1.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
+checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e"
dependencies = [
"percent-encoding",
]
@@ -7622,7 +7621,7 @@ dependencies = [
[[package]]
name = "jsonb"
version = "0.5.6"
-source = "git+https://github.com/GreptimeTeam/jsonb?rev=5a6472858d860ac034075c17253f41617bdfa956#5a6472858d860ac034075c17253f41617bdfa956"
+source = "git+https://github.com/GreptimeTeam/jsonb?rev=ae1ca9a26c65902dac9b53864bf502843c312ea5#ae1ca9a26c65902dac9b53864bf502843c312ea5"
dependencies = [
"byteorder",
"ethnum",
@@ -12092,6 +12091,7 @@ dependencies = [
"snafu 0.8.6",
"sql",
"sqlparser",
+ "stacker",
"store-api",
"substrait 1.4.0-alpha.0",
"table",
@@ -14287,7 +14287,6 @@ version = "1.4.0-alpha.0"
dependencies = [
"api",
"arrow-buffer 59.2.0",
- "arrow-schema 59.2.0",
"chrono",
"common-base",
"common-catalog",
@@ -16598,9 +16597,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
[[package]]
name = "url"
-version = "2.5.7"
+version = "2.5.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "08bc136a29a3d1758e07a9cca267be308aeebf5cfd5a10f3f67ab2097683ef5b"
+checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a"
dependencies = [
"form_urlencoded",
"idna",
diff --git a/Cargo.toml b/Cargo.toml
index f6b7a6812e1..434803ad872 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -177,7 +177,7 @@ icu_properties = "2.0.1"
indicatif = "0.17"
intern-arc = "0.6.2"
itertools = "0.14"
-jsonb = { git = "https://github.com/GreptimeTeam/jsonb", rev = "5a6472858d860ac034075c17253f41617bdfa956", default-features = false, features = [
+jsonb = { git = "https://github.com/GreptimeTeam/jsonb", rev = "ae1ca9a26c65902dac9b53864bf502843c312ea5", default-features = false, features = [
"databend",
] }
lazy_static = "1.4"
@@ -278,7 +278,7 @@ tokio-rustls = { version = "0.26.2", default-features = false }
tokio-stream = "0.1"
tokio-util = { version = "0.7", features = ["io-util", "compat"] }
toml = "0.8.8"
-url = "2.3"
+url = "2.5.9"
# Pin below 0.14.5 to avoid the `connection_timeout_future` "async fn resumed after
# completion" panic (greptimedb#8265 / grpc-rust#2522). Remove once tonic ships a fix.
tonic = { version = "0.14, <0.14.5", features = ["tls-aws-lc", "gzip", "zstd"] }
diff --git a/config/config.md b/config/config.md
index 911411ee655..66dd70d7920 100644
--- a/config/config.md
+++ b/config/config.md
@@ -102,7 +102,7 @@
| `prom_store` | -- | -- | Prometheus remote storage options |
| `prom_store.enable` | Bool | `true` | Whether to enable Prometheus remote write and read in HTTP API. |
| `prom_store.with_metric_engine` | Bool | `true` | Whether to store the data from Prometheus remote write in metric engine. |
-| `prom_store.prom_validation_mode` | String | `strict` | Whether to enable validation for Prometheus remote write requests.
Available options:
- strict: deny invalid UTF-8 strings (default).
- lossy: allow invalid UTF-8 strings, replace invalid characters with REPLACEMENT_CHARACTER(U+FFFD).
- unchecked: do not valid strings. |
+| `prom_store.prom_validation_mode` | String | `strict` | Whether to enable validation for Prometheus remote write requests.
Available options:
- strict: deny invalid UTF-8 strings (default).
- lossy: allow invalid UTF-8 strings, replace invalid characters with REPLACEMENT_CHARACTER(U+FFFD).
- unchecked: same as `lossy`. Kept for compatibility. |
| `wal` | -- | -- | The WAL options. |
| `wal.provider` | String | `raft_engine` | The provider of the WAL.
- `raft_engine`: the wal is stored in the local file system by raft-engine.
- `kafka`: it's remote wal that data is stored in Kafka.
- `experimental_object_store`: the wal is stored as objects in an object store.
**Notes: experimental.** |
| `wal.dir` | String | Unset | The directory to store the WAL files.
**It's only used when the provider is `raft_engine`**. |
@@ -145,6 +145,7 @@
| `procedure.max_running_procedures` | Integer | `128` | Max running procedures.
The maximum number of procedures that can be running at the same time.
If the number of running procedures exceeds this limit, the procedure will be rejected. |
| `query` | -- | -- | The query engine options. |
| `query.experimental_native_promql` | Bool | `false` | Enable experimental native PromQL execution for compatible queries.
This is the engine-wide default: a session
SET query.experimental_native_promql = true or a per-request
query.experimental_native_promql option overrides it, in that order.
Default: false |
+| `query.experimental_enable_factorized_join_agg` | Bool | `false` | Experimental opt-in for shape-based AVG/SUM join aggregation; default false. |
| `query.parallelism` | Integer | `0` | Parallelism of the query engine.
Default to 0, which means the number of CPU cores. |
| `query.memory_pool_size` | String | 0 | Memory pool size for query execution operators (aggregation, sorting, join,
and internal series merges during table scans).
Supports absolute size (e.g., "2GB", "4GB") or percentage of system memory (e.g., "20%").
Setting it to 0 disables the limit. Defaults to 0 (unlimited); this example sets it to `50%`.
When this limit is reached, queries will fail with ResourceExhausted error.
Projected Parquet row groups and streamed scan batches use scan_memory_limit separately. |
| `query.experimental_memory_pool_policy` | String | `greedy` | Experimental memory pool allocation policy:
- "greedy" (default): first-come-first-served allocation; preserves current behavior.
- "fair": divides available memory among spillable operators and may spill earlier.
Only effective when `memory_pool_size` is bounded (>0). |
@@ -386,7 +387,7 @@
| `prom_store` | -- | -- | Prometheus remote storage options |
| `prom_store.enable` | Bool | `true` | Whether to enable Prometheus remote write and read in HTTP API. |
| `prom_store.with_metric_engine` | Bool | `true` | Whether to store the data from Prometheus remote write in metric engine. |
-| `prom_store.prom_validation_mode` | String | `strict` | Whether to enable validation for Prometheus remote write requests.
Available options:
- strict: deny invalid UTF-8 strings (default).
- lossy: allow invalid UTF-8 strings, replace invalid characters with REPLACEMENT_CHARACTER(U+FFFD).
- unchecked: do not valid strings. |
+| `prom_store.prom_validation_mode` | String | `strict` | Whether to enable validation for Prometheus remote write requests.
Available options:
- strict: deny invalid UTF-8 strings (default).
- lossy: allow invalid UTF-8 strings, replace invalid characters with REPLACEMENT_CHARACTER(U+FFFD).
- unchecked: same as `lossy`. Kept for compatibility. |
| `meta_client` | -- | -- | The metasrv client options. |
| `meta_client.metasrv_addrs` | Array | -- | The addresses of the metasrv. |
| `meta_client.timeout` | String | `3s` | Operation timeout. |
@@ -398,6 +399,7 @@
| `meta_client.metadata_cache_tti` | String | `5m` | -- |
| `query` | -- | -- | The query engine options. |
| `query.experimental_native_promql` | Bool | `false` | Enable experimental native PromQL execution for compatible standalone queries.
Requires in-process region transport. This is the engine-wide default: a
session SET query.experimental_native_promql = true or a per-request
query.experimental_native_promql option overrides it, in that order.
Default: false |
+| `query.experimental_enable_factorized_join_agg` | Bool | `false` | Experimental opt-in for shape-based AVG/SUM join aggregation; default false. |
| `query.parallelism` | Integer | `0` | Parallelism of the query engine.
Default to 0, which means the number of CPU cores. |
| `query.allow_query_fallback` | Bool | `false` | Whether to allow query fallback when push down optimize fails.
Default to false, meaning when push down optimize failed, return error msg |
| `query.memory_pool_size` | String | 0 | Memory pool size for query execution operators (aggregation, sorting, join).
Supports absolute size (e.g., "4GB", "8GB") or percentage of system memory (e.g., "30%").
Setting it to 0 disables the limit. Defaults to 0 (unlimited); this example sets it to `50%`.
When this limit is reached, queries will fail with ResourceExhausted error.
This pool applies to operators on this frontend. Datanodes use their own query
pools for local operators and internal series merges during table scans. |
@@ -632,6 +634,7 @@
| `wal.on_corrupted_segment` | String | `skip` | What a read does with a segment that still does not decode after a second fetch, because its checksum does not match or its content disagrees with its footer entry.
- `skip`: the segment is skipped and recorded as a WAL hole of its region, a metric is incremented and a warning is logged; the other regions of the object are unaffected (the default).
- `fail`: the read fails, so the region does not open.
**It's only used when the provider is `experimental_object_store`**. |
| `wal.accept_missing_history` | Bool | `false` | Whether a region opens although the WAL objects under the prefix do not hold its history.
An existing region fails to open when the prefix held no object when the WAL opened, or when the flushed entry id of the region names an object above every object of the prefix that holds entries. Both happen after `storage_provider`, or the bucket or root of the provider it names, changed without the WAL objects being copied, or after the objects were deleted.
To move the WAL, stop the instance, copy every object under the prefix to the new location and then change the configuration; the regions open with all their writes.
When the old WAL is lost, set this to `true` for one start: the regions open without their writes that were not flushed, which are lost, a warning names each region, and `greptime_logstore_object_store_wal_missing_history_accepted_total` counts them. Turn it off again once the instance has written to the WAL after that start; until then a later start refuses a region whose flushed entry id names an object above every object of the prefix that holds entries.
**It's only used when the provider is `experimental_object_store`**. |
| `query` | -- | -- | The query engine options. |
+| `query.experimental_enable_factorized_join_agg` | Bool | `false` | Experimental opt-in for shape-based AVG/SUM join aggregation; default false. |
| `query.parallelism` | Integer | `0` | Parallelism of the query engine.
Default to 0, which means the number of CPU cores. |
| `query.memory_pool_size` | String | 0 | Memory pool size for query execution operators (aggregation, sorting, join,
and internal series merges during table scans).
Supports absolute size (e.g., "2GB", "4GB") or percentage of system memory (e.g., "20%").
Setting it to 0 disables the limit. Defaults to 0 (unlimited); this example sets it to `50%`.
When this limit is reached, queries will fail with ResourceExhausted error.
Projected Parquet row groups and streamed scan batches use scan_memory_limit separately. |
| `query.experimental_memory_pool_policy` | String | `greedy` | Experimental memory pool allocation policy:
- "greedy" (default): first-come-first-served allocation; preserves current behavior.
- "fair": divides available memory among spillable operators and may spill earlier.
Only effective when `memory_pool_size` is bounded (>0). |
@@ -824,6 +827,7 @@
| `tracing` | -- | -- | The tracing options. Only effect when compiled with `tokio-console` feature. |
| `tracing.tokio_console_addr` | String | Unset | The tokio console address. |
| `query` | -- | -- | -- |
+| `query.experimental_enable_factorized_join_agg` | Bool | `false` | Experimental opt-in for shape-based AVG/SUM join aggregation; default false. |
| `query.parallelism` | Integer | `1` | Parallelism of the query engine for query sent by flownode.
Default to 1, so it won't use too much cpu or memory |
| `query.memory_pool_size` | String | 0 | Memory pool size for query execution operators (aggregation, sorting, join).
Supports absolute size (e.g., "1GB", "2GB") or percentage of system memory (e.g., "20%").
Setting it to 0 disables the limit. Defaults to 0 (unlimited); this example sets it to `50%`.
When this limit is reached, queries will fail with ResourceExhausted error.
NOTE: This does NOT limit memory used by table scans. |
| `query.experimental_memory_pool_policy` | String | `greedy` | Experimental memory pool allocation policy:
- "greedy" (default): first-come-first-served allocation; preserves current behavior.
- "fair": divides available memory among spillable operators and may spill earlier.
Only effective when `memory_pool_size` is bounded (>0). |
diff --git a/config/datanode.example.toml b/config/datanode.example.toml
index 0b79313b159..6a3619311ef 100644
--- a/config/datanode.example.toml
+++ b/config/datanode.example.toml
@@ -335,6 +335,8 @@ overwrite_entry_start_id = false
## The query engine options.
[query]
+## Experimental opt-in for shape-based AVG/SUM join aggregation; default false.
+experimental_enable_factorized_join_agg = false
## Parallelism of the query engine.
## Default to 0, which means the number of CPU cores.
diff --git a/config/flownode.example.toml b/config/flownode.example.toml
index 837e1b51d9e..63a84c69672 100644
--- a/config/flownode.example.toml
+++ b/config/flownode.example.toml
@@ -153,6 +153,8 @@ default_ratio = 1.0
#+ tokio_console_addr = "127.0.0.1"
[query]
+## Experimental opt-in for shape-based AVG/SUM join aggregation; default false.
+experimental_enable_factorized_join_agg = false
## Parallelism of the query engine for query sent by flownode.
## Default to 1, so it won't use too much cpu or memory
diff --git a/config/frontend.example.toml b/config/frontend.example.toml
index 72da7dd199b..fa1a99d185a 100644
--- a/config/frontend.example.toml
+++ b/config/frontend.example.toml
@@ -338,7 +338,7 @@ with_metric_engine = true
## Available options:
## - strict: deny invalid UTF-8 strings (default).
## - lossy: allow invalid UTF-8 strings, replace invalid characters with REPLACEMENT_CHARACTER(U+FFFD).
-## - unchecked: do not valid strings.
+## - unchecked: same as `lossy`. Kept for compatibility.
prom_validation_mode = "strict"
@@ -377,6 +377,9 @@ metadata_cache_tti = "5m"
## query.experimental_native_promql option overrides it, in that order.
## Default: false
#+ experimental_native_promql = false
+## Experimental opt-in for shape-based AVG/SUM join aggregation; default false.
+experimental_enable_factorized_join_agg = false
+
## Parallelism of the query engine.
## Default to 0, which means the number of CPU cores.
parallelism = 0
diff --git a/config/standalone.example.toml b/config/standalone.example.toml
index f1066ce782b..f8d2c9ac7ee 100644
--- a/config/standalone.example.toml
+++ b/config/standalone.example.toml
@@ -318,7 +318,7 @@ with_metric_engine = true
## Available options:
## - strict: deny invalid UTF-8 strings (default).
## - lossy: allow invalid UTF-8 strings, replace invalid characters with REPLACEMENT_CHARACTER(U+FFFD).
-## - unchecked: do not valid strings.
+## - unchecked: same as `lossy`. Kept for compatibility.
prom_validation_mode = "strict"
@@ -570,6 +570,9 @@ max_running_procedures = 128
## query.experimental_native_promql option overrides it, in that order.
## Default: false
#+ experimental_native_promql = false
+## Experimental opt-in for shape-based AVG/SUM join aggregation; default false.
+experimental_enable_factorized_join_agg = false
+
## Parallelism of the query engine.
## Default to 0, which means the number of CPU cores.
parallelism = 0
diff --git a/cyborg/bin/follow-up-docs-issue.ts b/cyborg/bin/follow-up-docs-issue.ts
index 09ef5db2445..943a9cbab9a 100644
--- a/cyborg/bin/follow-up-docs-issue.ts
+++ b/cyborg/bin/follow-up-docs-issue.ts
@@ -26,8 +26,7 @@ import {
// @ts-expect-error moduleResolution:nodenext issue 54523
import {RequestError} from "@octokit/request-error";
-const needFollowUpDocs = "[x] This PR requires documentation updates."
-const labelDocsNotRequired = "docs-not-required"
+const needFollowUpDocs = /\[x\] This PR requires documentation updates\./i
const labelDocsRequired = "docs-required"
async function main() {
@@ -44,19 +43,9 @@ async function main() {
}
switch (payload.action) {
- case "opened": {
- const client = obtainClient("GITHUB_TOKEN")
- await updateDocsLabels(client, owner, repo, number, checkPullRequestOpenedEvent(payload as PullRequestOpenedEvent))
- break
- }
+ case "opened":
case "edited": {
- const followUpDocs = checkPullRequestEditedEvent(payload as PullRequestEditedEvent)
- if (followUpDocs === undefined) {
- core.info("Docs checkbox state unchanged; leaving labels as-is.")
- return
- }
- const client = obtainClient("GITHUB_TOKEN")
- await updateDocsLabels(client, owner, repo, number, followUpDocs)
+ await syncDocsLabel(obtainClient("GITHUB_TOKEN"), owner, repo, payload)
break
}
case "closed": {
@@ -87,17 +76,17 @@ async function main() {
}
}
-async function updateDocsLabels(client: ReturnType, owner: string, repo: string, number: number, followUpDocs: boolean) {
- if (followUpDocs) {
+export async function syncDocsLabel(client: ReturnType, owner: string, repo: string, event: PullRequestOpenedEvent | PullRequestEditedEvent) {
+ const { number, body } = event.pull_request
+ const previous = event.action === "opened" ? null : event.changes.body?.from ?? body
+ if (needFollowUpDocs.test(previous ?? "") === needFollowUpDocs.test(body ?? "")) return
+
+ // A newer checkbox edit can arrive while this run is waiting.
+ const { data: pr } = await client.rest.pulls.get({ owner, repo, pull_number: number })
+ const required = needFollowUpDocs.test(pr.body ?? "")
+ if (pr.labels.some(label => label.name === labelDocsRequired) === required) return
+ if (required) {
core.info("Follow up docs.")
- await client.rest.issues.removeLabel({
- owner, repo, issue_number: number, name: labelDocsNotRequired,
- }).catch((e: RequestError) => {
- if (e.status != 404) {
- throw e;
- }
- core.debug(`Label ${labelDocsNotRequired} not exist.`)
- })
await client.rest.issues.addLabels({
owner, repo, issue_number: number, labels: [labelDocsRequired],
})
@@ -111,9 +100,6 @@ async function updateDocsLabels(client: ReturnType, owner:
}
core.debug(`Label ${labelDocsRequired} not exist.`)
})
- await client.rest.issues.addLabels({
- owner, repo, issue_number: number, labels: [labelDocsNotRequired],
- })
}
}
@@ -165,24 +151,4 @@ async function waitForPendingLabelUpdates(client: ReturnType {
+ const client = getOctokit('test');
+ const unchecked = '- [ ] This PR requires documentation updates.';
+ const checked = '- [X] This PR requires documentation updates. See the docs PR.';
+ let current = {body: unchecked, labels: [{name: 'docs-required'}]};
+ const get = t.mock.method(client.rest.pulls, 'get', async () => ({data: current}));
+ const writes: string[] = [];
+ t.mock.method(client.rest.issues, 'addLabels', async ({labels}) => writes.push(`add ${labels.join(', ')}`));
+ t.mock.method(client.rest.issues, 'removeLabel', async ({name}) => writes.push(`remove ${name}`));
+
+ const pr = {number: 1, body: unchecked};
+ const open = {action: 'opened', pull_request: pr} as PullRequestOpenedEvent;
+ const edit = {action: 'edited', pull_request: pr, changes: {}} as PullRequestEditedEvent;
+ await syncDocsLabel(client, 'owner', 'repo', open);
+ await syncDocsLabel(client, 'owner', 'repo', edit);
+ edit.changes.body = {from: unchecked + '\nOld nightly checkbox'};
+ await syncDocsLabel(client, 'owner', 'repo', edit);
+ assert.equal(get.mock.callCount(), 0);
+
+ edit.changes.body = {from: checked};
+ await syncDocsLabel(client, 'owner', 'repo', edit);
+ current = {body: checked, labels: []};
+ await syncDocsLabel(client, 'owner', 'repo', edit);
+ assert.deepEqual(writes, ['remove docs-required', 'add docs-required']);
+});
diff --git a/docs/formats/mito-samples.md b/docs/formats/mito-samples.md
index 5008babf5e6..5babdc27cbe 100644
--- a/docs/formats/mito-samples.md
+++ b/docs/formats/mito-samples.md
@@ -1,4 +1,28 @@
-# Mito columnar samples format
+# Narthex format: samples
+
+The **Narthex format**, selected by `sst_format = 'narthex'`, is optimized
+for Prometheus-style metric data. It separates series identities and string tags
+from timestamped numeric samples.
+
+The format has two artifact roles: `NarthexSamples` owns sample data, and
+`NarthexSeriesIndex` indexes series and references the samples it covers.
+Region manifests serialize these roles as `narthex_samples` and
+`narthex_series_index`.
+
+## Authoritative storage and derived sidecars
+
+With `sst_format = 'narthex'`, samples are authoritative SSTs. Each artifact owns
+`//manifest.json` and its `part-.samples` or
+`part-.series` objects. The region manifest records the manifest size and a `parts` array in part-ID order.
+Each part record contains its encoded `file_size` in bytes. Series indexes reference region-qualified sample file IDs without owning those
+samples. Both artifact types use ordinary SST lifetimes and reclamation.
+
+The same codecs also support rebuildable sidecars over Parquet SSTs. The catalog
+paths, source-SST coverage, daily consolidation, and local-cache rollout described
+below apply to that sidecar mode. They do not make authoritative Narthex samples
+rebuildable or subject them to local-cache eviction.
+
+## Wire specification
This document specifies the version 1 on-disk layout, encodings, ordering rules,
and validation limits for samples artifacts. The version number stays 1: the
@@ -17,7 +41,7 @@ applies to an artifact of the earlier layout of this format, whose keys sat insi
the block descriptors: its `identity_encoding` value is the older
`exact-sparse-key`, so it is refused when the manifest is opened rather than when a
part is first read. It shares artifact conventions with
-[Mito columnar series format](mito-series.md).
+[Narthex series-index format](mito-series.md).
Samples store nullable Float64 fields, timestamps, sequences, and operation types
in single-series blocks bounded by rows and decoded bytes.
diff --git a/docs/formats/mito-series.md b/docs/formats/mito-series.md
index 66ea4bd4017..ae5f2d4d8fb 100644
--- a/docs/formats/mito-series.md
+++ b/docs/formats/mito-series.md
@@ -1,4 +1,28 @@
-# Mito columnar series format
+# Narthex format: series index
+
+The **Narthex format**, selected by `sst_format = 'narthex'`, is optimized
+for Prometheus-style metric data. It separates series identities and string tags
+from timestamped numeric samples.
+
+The format has two artifact roles: `NarthexSamples` owns sample data, and
+`NarthexSeriesIndex` indexes series and references the samples it covers.
+Region manifests serialize these roles as `narthex_samples` and
+`narthex_series_index`.
+
+## Authoritative storage and derived sidecars
+
+With `sst_format = 'narthex'`, samples are authoritative SSTs. Each artifact owns
+`//manifest.json` and its `part-.samples` or
+`part-.series` objects. The region manifest records the manifest size and a `parts` array in part-ID order.
+Each part record contains its encoded `file_size` in bytes. Series indexes reference region-qualified sample file IDs without owning those
+samples. Both artifact types use ordinary SST lifetimes and reclamation.
+
+The same codecs also support rebuildable sidecars over Parquet SSTs. The catalog
+paths, source-SST coverage, daily consolidation, and local-cache rollout described
+below apply to that sidecar mode. They do not make authoritative Narthex samples
+rebuildable or subject them to local-cache eviction.
+
+## Wire specification
This document specifies the version 1 on-disk layout, encodings, ordering rules,
and validation limits for series-index artifacts. The version number stays 1: the
@@ -12,7 +36,7 @@ number and may contain an already merged row that cannot be told apart from a
complete one; nothing else in the artifact distinguishes them. A manifest that
does not carry `identity_encoding` is therefore rejected, and its artifact rebuilt
from SSTs; there is no dual reader. For samples, see
-[Mito columnar samples format](mito-samples.md).
+[Narthex samples format](mito-samples.md).
## Artifact manifest
@@ -93,8 +117,8 @@ order are not wire contracts. Reject trailing bytes in decoded structures.
### Column payloads
-An artifact indexes the series in one Mito series-index bucket. Authoritative
-data remains in Parquet SSTs; these indexes can be rebuilt. Each record contains:
+An artifact indexes the series in one Mito series-index bucket. In sidecar mode, authoritative
+data remains in Parquet SSTs and these indexes can be rebuilt. Each record contains:
| Logical column | Type | Storage |
| --- | --- | --- |
diff --git a/docs/how-to/how-to-change-log-level-on-the-fly.md b/docs/how-to/how-to-change-log-level-on-the-fly.md
index c3bf2602a26..e8e19bafed4 100644
--- a/docs/how-to/how-to-change-log-level-on-the-fly.md
+++ b/docs/how-to/how-to-change-log-level-on-the-fly.md
@@ -2,6 +2,8 @@
## HTTP API
+When the server is started with a user provider, add `-u :` to the `curl` commands in this guide.
+
example:
```bash
curl --data "trace,flow=debug" 127.0.0.1:4000/debug/log_level
diff --git a/docs/how-to/how-to-profile-cpu.md b/docs/how-to/how-to-profile-cpu.md
index ff50b0ea44c..65ce6910829 100644
--- a/docs/how-to/how-to-profile-cpu.md
+++ b/docs/how-to/how-to-profile-cpu.md
@@ -1,6 +1,8 @@
# Profiling CPU
## HTTP API
+When the server is started with a user provider, add `-u :` to the `curl` commands below.
+
Sample at 99 Hertz, for 5 seconds, output report in [protobuf format](https://github.com/google/pprof/blob/master/proto/profile.proto).
```bash
curl -X POST -s '0:4000/debug/prof/cpu' > /tmp/pprof.out
diff --git a/docs/how-to/how-to-profile-memory.md b/docs/how-to/how-to-profile-memory.md
index da4e3b6f0a7..ca9653c0ebf 100644
--- a/docs/how-to/how-to-profile-memory.md
+++ b/docs/how-to/how-to-profile-memory.md
@@ -58,6 +58,22 @@ enable_heap_profiling = true
To disable memory profiling, set `enable_heap_profiling` to `false`.
+### Authentication
+
+When the server is started with a user provider, the `/debug` endpoints require HTTP Basic authentication. Add `-u :` to the `curl` commands in this guide.
+
+`dump.sh` reads credentials from the curl config file set in `GREPTIME_CURL_CONFIG`. Create the file with mode `600` and the following content:
+
+```
+user = ":"
+```
+
+Then run the script:
+
+```bash
+GREPTIME_CURL_CONFIG=/path/to/curl.conf ./dump.sh
+```
+
### Memory profiling control
You can control heap profiling activation using the new HTTP APIs:
diff --git a/docs/how-to/memory-profile-scripts/scripts/dump.sh b/docs/how-to/memory-profile-scripts/scripts/dump.sh
index d84bee75a56..6a7ba8aba96 100755
--- a/docs/how-to/memory-profile-scripts/scripts/dump.sh
+++ b/docs/how-to/memory-profile-scripts/scripts/dump.sh
@@ -11,6 +11,17 @@
threshold_kb=$((20 * 1024))
sleep_interval=$((10 * 60))
+# Servers with a user provider require credentials on /debug endpoints. Set
+# GREPTIME_CURL_CONFIG to a curl config file containing `user = ":"`.
+curl_args=(-sf -X POST)
+if [ -n "${GREPTIME_CURL_CONFIG:-}" ]; then
+ if [ ! -r "$GREPTIME_CURL_CONFIG" ]; then
+ echo "$(date): Cannot read curl config file: '$GREPTIME_CURL_CONFIG'."
+ exit 1
+ fi
+ curl_args+=(--config "$GREPTIME_CURL_CONFIG")
+fi
+
# Variable to store the last measured memory usage in KB
last_mem_kb=0
@@ -55,7 +66,7 @@ while true; do
timestamp=$(date +%Y%m%d%H%M%S)
profile_file="greptime-${timestamp}.gprof"
# Execute curl and capture output to file
- if curl -sf -X POST localhost:4000/debug/prof/mem > "$profile_file"; then
+ if curl "${curl_args[@]}" localhost:4000/debug/prof/mem > "$profile_file"; then
echo "$(date): Memory profile saved to $profile_file"
else
echo "$(date): Failed to dump memory profile (curl exit code: $?)."
diff --git a/docs/how-to/query-options.md b/docs/how-to/query-options.md
index 3fdaa55979d..219160937c8 100644
--- a/docs/how-to/query-options.md
+++ b/docs/how-to/query-options.md
@@ -6,6 +6,7 @@ Query options adjust selected behavior for a connection or request; they are not
| --- | --- | --- |
| `query.parallelism` | `query_parallelism`, `query.parallelism` | Integer `1`–`1024`; server default `0` means automatic CPU-based parallelism. This is not a resource-pool limit. |
| `query.allow_query_fallback` | `query_fallback`, `allow_query_fallback`, `query.allow_query_fallback` (legacy `ALLOW_QUERY_FALLBACK` syntax / `query_fallback` hint also work) | `true` or `false` |
+| `query.experimental_enable_factorized_join_agg` | `experimental_enable_factorized_join_agg`, `query.experimental_enable_factorized_join_agg` | `true` or `false`; experimental opt-in for shape-based AVG/SUM join aggregation. Server default `false`; unset inherits it. |
| `query.enable_remote_dynamic_filter_pushdown` | canonical name | `true` or `false` |
| `datafusion.optimizer.*` | canonical name | Keys, types, defaults, and validation come from the linked DataFusion version (for example, numeric `max_passes` and Boolean `filter_null_join_keys`). |
diff --git a/licenserc-enterprise.toml b/licenserc-enterprise.toml
index 22b35ded3e8..979f8d13fda 100644
--- a/licenserc-enterprise.toml
+++ b/licenserc-enterprise.toml
@@ -36,6 +36,7 @@ includes = [
"src/mito2/src/compaction/multi_region/worker.rs",
"src/mito2/src/compaction/multi_region/writer.rs",
"src/mito2/src/compaction/multi_region/tests.rs",
+ "src/mito2/src/sst/upload/buffered.rs",
"src/common/function/src/admin/purge_table.rs",
"src/catalog/src/system_schema/information_schema/recycle_bin.rs",
"src/common/meta/src/ddl/purge_dropped_table.rs",
diff --git a/licenserc.toml b/licenserc.toml
index 172a6af5d61..f004568e9d2 100644
--- a/licenserc.toml
+++ b/licenserc.toml
@@ -52,6 +52,7 @@ excludes = [
"src/mito2/src/compaction/multi_region/worker.rs",
"src/mito2/src/compaction/multi_region/writer.rs",
"src/mito2/src/compaction/multi_region/tests.rs",
+ "src/mito2/src/sst/upload/buffered.rs",
"src/common/function/src/admin/purge_table.rs",
"src/catalog/src/system_schema/information_schema/recycle_bin.rs",
"src/common/meta/src/ddl/purge_dropped_table.rs",
diff --git a/src/catalog/src/kvbackend/client.rs b/src/catalog/src/kvbackend/client.rs
index 402af1d9865..4c4ba231b7a 100644
--- a/src/catalog/src/kvbackend/client.rs
+++ b/src/catalog/src/kvbackend/client.rs
@@ -26,7 +26,9 @@ use common_meta::error::{
};
use common_meta::kv_backend::read_only::ReadOnlyKvBackend;
use common_meta::kv_backend::txn::{Txn, TxnResponse};
-use common_meta::kv_backend::{KvBackend, KvBackendRef, TxnService};
+use common_meta::kv_backend::{
+ KvBackend, KvBackendCapabilities, KvBackendRef, TxnCapability, TxnService,
+};
use common_meta::rpc::KeyValue;
use common_meta::rpc::store::{
BatchDeleteRequest, BatchDeleteResponse, BatchGetRequest, BatchGetResponse, BatchPutRequest,
@@ -129,13 +131,17 @@ impl TxnService for CachedKvBackend {
self.kv_backend.txn(txn).await
}
- fn max_txn_ops(&self) -> usize {
- self.kv_backend.max_txn_ops()
+ fn txn_capability(&self) -> Option {
+ self.kv_backend.txn_capability()
}
}
#[async_trait::async_trait]
impl KvBackend for CachedKvBackend {
+ fn capabilities(&self) -> KvBackendCapabilities {
+ self.kv_backend.capabilities()
+ }
+
fn name(&self) -> &str {
&self.name
}
@@ -389,10 +395,6 @@ impl TxnService for MetaKvBackend {
}
.fail()
}
-
- fn max_txn_ops(&self) -> usize {
- usize::MAX
- }
}
/// Implement `KvBackend` trait for `MetaKvBackend` instead of opendal's `Accessor` since
@@ -671,6 +673,7 @@ mod tests {
let meta_client = Arc::new(MetaClientBuilder::frontend_default_options().build());
let backend = new_read_only_meta_kv_backend(meta_client);
+ assert_eq!(backend.txn_capability(), None);
let result = backend
.txn(Txn::new().and_then(vec![TxnOp::Get(b"k1".to_vec())]))
.await;
diff --git a/src/cmd/src/bin/query_perf_fixture/direct_sst.rs b/src/cmd/src/bin/query_perf_fixture/direct_sst.rs
index e95b5244026..a3a670a5a0f 100644
--- a/src/cmd/src/bin/query_perf_fixture/direct_sst.rs
+++ b/src/cmd/src/bin/query_perf_fixture/direct_sst.rs
@@ -302,6 +302,7 @@ fn file_meta_from_sst_info(
level: 0,
file_size: info.file_size,
max_row_group_uncompressed_size: info.max_row_group_uncompressed_size,
+ max_row_group_decoded_size: info.max_row_group_decoded_size,
available_indexes: Default::default(),
indexes: Default::default(),
index_file_size: 0,
@@ -474,6 +475,9 @@ pub(super) async fn run_direct_sst(args: DirectArgs) {
..Default::default()
};
let infos = match format {
+ FormatType::Narthex => {
+ unimplemented!("direct SST fixtures only support Parquet formats")
+ }
FormatType::Flat => writer.write_all_flat(source, Some(sequence), &opts).await,
FormatType::PrimaryKey => {
writer
diff --git a/src/cmd/src/datanode/parquet_rewrite.rs b/src/cmd/src/datanode/parquet_rewrite.rs
index b04db93edcb..2df3f7657fd 100644
--- a/src/cmd/src/datanode/parquet_rewrite.rs
+++ b/src/cmd/src/datanode/parquet_rewrite.rs
@@ -17,6 +17,9 @@ use std::path::{Path, PathBuf};
use clap::Parser;
use datatypes::arrow::record_batch::RecordBatchReader;
+use mito2::sst::parquet::{
+ MAX_ROW_GROUP_VALUE_BYTES_KEY, MAX_ROW_VALUE_WIDTH_KEY, RowGroupValueBytes,
+};
use parquet::arrow::ArrowWriter;
use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
use parquet::basic::{BrotliLevel, Compression, Encoding, GzipLevel, ZstdLevel};
@@ -151,11 +154,18 @@ impl ParquetRewriteCommand {
let props = load_rewrite_properties(properties)?;
let input_reader = SerializedFileReader::new(open_file(&self.input)?)
.map_err(|e| parquet_error("read source parquet metadata", &self.input, e))?;
- let key_value_metadata = input_reader
+ let mut key_value_metadata = input_reader
.metadata()
.file_metadata()
.key_value_metadata()
.cloned();
+ // The decoded value sizes of row groups depend on the row group boundaries, which the
+ // rewrite may change. Recompute them for the output instead of copying them.
+ let had_value_bytes = key_value_metadata.as_mut().is_some_and(|kvs| {
+ let len = kvs.len();
+ kvs.retain(|kv| !is_row_group_value_bytes_key(&kv.key));
+ kvs.len() != len
+ });
let mut reader_builder = ParquetRecordBatchReaderBuilder::try_new(open_file(&self.input)?)
.map_err(|e| parquet_error("open source parquet", &self.input, e))?;
@@ -171,16 +181,29 @@ impl ParquetRewriteCommand {
let schema = reader.schema();
let writer_props = build_writer_properties(props, key_value_metadata)?;
+ // The rewrite never sets `max_row_group_bytes`, so row groups are cut by row count only.
+ let mut value_bytes = had_value_bytes.then(|| {
+ RowGroupValueBytes::new(writer_props.max_row_group_row_count().unwrap_or(usize::MAX))
+ });
let mut writer = ArrowWriter::try_new(create_file(output)?, schema, Some(writer_props))
.map_err(|e| parquet_error("create parquet writer", output, e))?;
for batch in reader {
let batch =
batch.map_err(|e| parquet_error("read parquet batch", &self.input, e.into()))?;
+ if let Some(value_bytes) = value_bytes.as_mut() {
+ value_bytes.update(&batch);
+ }
writer
.write(&batch)
.map_err(|e| parquet_error("write parquet batch", output, e))?;
}
+ for kv in value_bytes
+ .map(RowGroupValueBytes::into_key_values)
+ .unwrap_or_default()
+ {
+ writer.append_key_value_metadata(kv);
+ }
writer
.close()
.map_err(|e| parquet_error("close parquet writer", output, e))?;
@@ -190,6 +213,10 @@ impl ParquetRewriteCommand {
}
}
+fn is_row_group_value_bytes_key(key: &str) -> bool {
+ key == MAX_ROW_GROUP_VALUE_BYTES_KEY || key == MAX_ROW_VALUE_WIDTH_KEY
+}
+
fn infer_rewrite_properties(metadata: &ParquetMetaData) -> RewriteProperties {
let is_greptime_sst = metadata
.file_metadata()
@@ -551,6 +578,65 @@ mod tests {
);
}
+ #[test]
+ fn test_rewrite_recomputes_row_group_value_bytes() {
+ let dir = tempdir().unwrap();
+ let input = dir.path().join("input.parquet");
+ let output = dir.path().join("output.parquet");
+ // 16 rows of one repeated 1 KiB value, in row groups of 4 rows.
+ let schema = Arc::new(Schema::new(vec![Field::new("body", DataType::Utf8, false)]));
+ let value = "x".repeat(1024);
+ let batch = RecordBatch::try_new(
+ schema.clone(),
+ vec![Arc::new(StringArray::from(vec![value.as_str(); 16]))],
+ )
+ .unwrap();
+ let mut value_bytes = RowGroupValueBytes::new(4);
+ value_bytes.update(&batch);
+ let props = WriterProperties::builder()
+ .set_max_row_group_row_count(Some(4))
+ .set_key_value_metadata(Some(value_bytes.into_key_values()))
+ .build();
+ let mut writer =
+ ArrowWriter::try_new(File::create(&input).unwrap(), schema, Some(props)).unwrap();
+ writer.write(&batch).unwrap();
+ writer.close().unwrap();
+
+ let mut properties =
+ infer_rewrite_properties(&load_local_parquet_metadata(&input).unwrap());
+ properties.writer.max_row_group_row_count = Some(8);
+ let props_path = dir.path().join("props.toml");
+ std::fs::write(&props_path, toml::to_string(&properties).unwrap()).unwrap();
+ let command = ParquetRewriteCommand {
+ input,
+ output: Some(output.clone()),
+ properties: Some(props_path.clone()),
+ dump_properties: None,
+ batch_size: None,
+ overwrite: false,
+ };
+ command.rewrite(&output, &props_path).unwrap();
+
+ let rewritten = load_local_parquet_metadata(&output).unwrap();
+ assert_eq!(2, rewritten.num_row_groups());
+ let key_values = rewritten.file_metadata().key_value_metadata().unwrap();
+ let value_of = |key: &str| {
+ let values: Vec<_> = key_values
+ .iter()
+ .filter(|kv| kv.key == key)
+ .map(|kv| kv.value.clone().unwrap())
+ .collect();
+ assert_eq!(1, values.len());
+ values[0].clone()
+ };
+ // Doubling the row group doubles its decoded value bytes; the width per row is unchanged.
+ assert_eq!(
+ (8 * 1024).to_string(),
+ value_of(MAX_ROW_GROUP_VALUE_BYTES_KEY)
+ );
+ assert_eq!(1024.to_string(), value_of(MAX_ROW_VALUE_WIDTH_KEY));
+ }
+
#[test]
fn test_infer_truncation_settings_for_greptime_sst() {
let dir = tempdir().unwrap();
diff --git a/src/cmd/src/datanode/parquetbench.rs b/src/cmd/src/datanode/parquetbench.rs
index b05b5cf0753..0bdb53c39f5 100644
--- a/src/cmd/src/datanode/parquetbench.rs
+++ b/src/cmd/src/datanode/parquetbench.rs
@@ -345,6 +345,7 @@ impl ParquetbenchCommand {
level: 0,
file_size,
max_row_group_uncompressed_size: 0,
+ max_row_group_decoded_size: 0,
available_indexes: Default::default(),
indexes: Default::default(),
index_file_size: 0,
diff --git a/src/cmd/src/datanode/sst_replace.rs b/src/cmd/src/datanode/sst_replace.rs
index 04c5cc5ee09..b8dd39c0a60 100644
--- a/src/cmd/src/datanode/sst_replace.rs
+++ b/src/cmd/src/datanode/sst_replace.rs
@@ -22,6 +22,7 @@ use mito2::region::ManifestStats;
use mito2::sst::file::RegionFileId;
use mito2::sst::file_metadata::FileMetadataInterner;
use mito2::sst::location::{region_dir_from_table_dir, sst_file_path};
+use mito2::sst::parquet::max_row_group_decoded_size;
use object_store::ObjectStore;
use parquet::file::FOOTER_SIZE;
use parquet::file::metadata::{FooterTail, ParquetMetaDataReader};
@@ -172,6 +173,7 @@ impl SstReplaceCommand {
new_file.num_rows = new_num_rows;
new_file.num_row_groups = new_num_row_groups;
new_file.max_row_group_uncompressed_size = max_row_group_uncompressed_size(&parquet_meta);
+ new_file.max_row_group_decoded_size = max_row_group_decoded_size(&parquet_meta);
println!("{} Region: {}", "[ok]".green(), region_id);
println!("{} Target SST: {}", "[ok]".green(), target_path.cyan());
diff --git a/src/common/cache/src/metrics.rs b/src/common/cache/src/metrics.rs
index fd02c32b689..12da47e9747 100644
--- a/src/common/cache/src/metrics.rs
+++ b/src/common/cache/src/metrics.rs
@@ -43,6 +43,17 @@ pub struct OperationMetrics {
}
impl OperationMetrics {
+ /// Measures a fallible operation, including cancellation before completion.
+ pub async fn observe(
+ &self,
+ operation: impl Future