mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-11-28 05:34:02 +00:00
Merge upstream main into metadata COUNT core
Signed-off-by: aumnertic <aumnertic@gmail.com>
This commit is contained in:
+1
-1
@@ -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.
|
||||
|
||||
+72
-18
@@ -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.
|
||||
|
||||
@@ -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 <!-- nightly-merge -->
|
||||
- [ ] Skip nightly merge
|
||||
|
||||
<!--
|
||||
Eligible PRs enter the merge queue hourly from 02:10 through 08:10 Beijing time (UTC+8), up to five per run.
|
||||
Uncheck to opt out and remove the `merge nightly` label; this does not enable immediate merging.
|
||||
Check to opt out. To resume, uncheck the box and remove any manually applied `skip nightly merge` label.
|
||||
Maintainers can use **Merge when ready** to merge earlier.
|
||||
Changing this checkbox does not cancel an existing queue entry or manually enabled auto-merge.
|
||||
-->
|
||||
|
||||
@@ -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]*<!-- nightly-merge -->)?/i.exec(item.text);
|
||||
if (old) {
|
||||
const following = updated.slice(item.end).replace(/^(?:[ \t]*\r?\n)+ {0,3}<!--[\s\S]*?-->/, 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 };
|
||||
@@ -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('<!--') && line.lastIndexOf('<!--') > line.lastIndexOf('-->');
|
||||
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 };
|
||||
@@ -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 <!-- nightly-merge -->';
|
||||
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 <!-- nightly-merge -->';
|
||||
|
||||
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 + ' <!-- note --> 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\`\`\``,
|
||||
`<!--\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, '```', '<!--', 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, '<!--', oldHelp, '-->', '```', '',
|
||||
box + ' — waiting for a backport', '', '<!--', 'Author note', help, '-->', '',
|
||||
'<!--', oldHelp, '-->'
|
||||
].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';
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 <!-- nightly-merge -->\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 {
|
||||
|
||||
Generated
+6
-7
@@ -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",
|
||||
|
||||
+2
-2
@@ -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"] }
|
||||
|
||||
+6
-2
@@ -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.<br/>Available options:<br/>- strict: deny invalid UTF-8 strings (default).<br/>- lossy: allow invalid UTF-8 strings, replace invalid characters with REPLACEMENT_CHARACTER(U+FFFD).<br/>- unchecked: do not valid strings. |
|
||||
| `prom_store.prom_validation_mode` | String | `strict` | Whether to enable validation for Prometheus remote write requests.<br/>Available options:<br/>- strict: deny invalid UTF-8 strings (default).<br/>- lossy: allow invalid UTF-8 strings, replace invalid characters with REPLACEMENT_CHARACTER(U+FFFD).<br/>- unchecked: same as `lossy`. Kept for compatibility. |
|
||||
| `wal` | -- | -- | The WAL options. |
|
||||
| `wal.provider` | String | `raft_engine` | The provider of the WAL.<br/>- `raft_engine`: the wal is stored in the local file system by raft-engine.<br/>- `kafka`: it's remote wal that data is stored in Kafka.<br/>- `experimental_object_store`: the wal is stored as objects in an object store.<br/>**Notes: experimental.** |
|
||||
| `wal.dir` | String | Unset | The directory to store the WAL files.<br/>**It's only used when the provider is `raft_engine`**. |
|
||||
@@ -145,6 +145,7 @@
|
||||
| `procedure.max_running_procedures` | Integer | `128` | Max running procedures.<br/>The maximum number of procedures that can be running at the same time.<br/>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.<br/>This is the engine-wide default: a session<br/>SET query.experimental_native_promql = true or a per-request<br/>query.experimental_native_promql option overrides it, in that order.<br/>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.<br/>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,<br/>and internal series merges during table scans).<br/>Supports absolute size (e.g., "2GB", "4GB") or percentage of system memory (e.g., "20%").<br/>Setting it to 0 disables the limit. Defaults to 0 (unlimited); this example sets it to `50%`.<br/>When this limit is reached, queries will fail with ResourceExhausted error.<br/>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:<br/>- "greedy" (default): first-come-first-served allocation; preserves current behavior.<br/>- "fair": divides available memory among spillable operators and may spill earlier.<br/>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.<br/>Available options:<br/>- strict: deny invalid UTF-8 strings (default).<br/>- lossy: allow invalid UTF-8 strings, replace invalid characters with REPLACEMENT_CHARACTER(U+FFFD).<br/>- unchecked: do not valid strings. |
|
||||
| `prom_store.prom_validation_mode` | String | `strict` | Whether to enable validation for Prometheus remote write requests.<br/>Available options:<br/>- strict: deny invalid UTF-8 strings (default).<br/>- lossy: allow invalid UTF-8 strings, replace invalid characters with REPLACEMENT_CHARACTER(U+FFFD).<br/>- 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.<br/>Requires in-process region transport. This is the engine-wide default: a<br/>session SET query.experimental_native_promql = true or a per-request<br/>query.experimental_native_promql option overrides it, in that order.<br/>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.<br/>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.<br/>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).<br/>Supports absolute size (e.g., "4GB", "8GB") or percentage of system memory (e.g., "30%").<br/>Setting it to 0 disables the limit. Defaults to 0 (unlimited); this example sets it to `50%`.<br/>When this limit is reached, queries will fail with ResourceExhausted error.<br/>This pool applies to operators on this frontend. Datanodes use their own query<br/>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.<br/>- `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).<br/>- `fail`: the read fails, so the region does not open.<br/>**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.<br/>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.<br/>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.<br/>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.<br/>**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.<br/>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,<br/>and internal series merges during table scans).<br/>Supports absolute size (e.g., "2GB", "4GB") or percentage of system memory (e.g., "20%").<br/>Setting it to 0 disables the limit. Defaults to 0 (unlimited); this example sets it to `50%`.<br/>When this limit is reached, queries will fail with ResourceExhausted error.<br/>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:<br/>- "greedy" (default): first-come-first-served allocation; preserves current behavior.<br/>- "fair": divides available memory among spillable operators and may spill earlier.<br/>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.<br/>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).<br/>Supports absolute size (e.g., "1GB", "2GB") or percentage of system memory (e.g., "20%").<br/>Setting it to 0 disables the limit. Defaults to 0 (unlimited); this example sets it to `50%`.<br/>When this limit is reached, queries will fail with ResourceExhausted error.<br/>NOTE: This does NOT limit memory used by table scans. |
|
||||
| `query.experimental_memory_pool_policy` | String | `greedy` | Experimental memory pool allocation policy:<br/>- "greedy" (default): first-come-first-served allocation; preserves current behavior.<br/>- "fair": divides available memory among spillable operators and may spill earlier.<br/>Only effective when `memory_pool_size` is bounded (>0). |
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<typeof obtainClient>, owner: string, repo: string, number: number, followUpDocs: boolean) {
|
||||
if (followUpDocs) {
|
||||
export async function syncDocsLabel(client: ReturnType<typeof obtainClient>, 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<typeof obtainClient>, 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<typeof obtainClient
|
||||
core.warning("Timed out waiting for pending docbot runs; proceeding with the current label state.")
|
||||
}
|
||||
|
||||
function checkPullRequestOpenedEvent(event: PullRequestOpenedEvent): boolean {
|
||||
// @ts-ignore
|
||||
return event.pull_request.body?.includes(needFollowUpDocs)
|
||||
}
|
||||
|
||||
// Returns undefined when the checkbox state did not change in this edit, so the
|
||||
// caller leaves the labels untouched (preserving manual label overrides).
|
||||
function checkPullRequestEditedEvent(event: PullRequestEditedEvent): boolean | undefined {
|
||||
if (!event.changes.body) {
|
||||
// The body was not part of this edit (e.g. title-only edit).
|
||||
return undefined
|
||||
}
|
||||
const previous = event.changes.body.from.includes(needFollowUpDocs)
|
||||
const current = event.pull_request.body?.includes(needFollowUpDocs) ?? false
|
||||
if (previous === current) {
|
||||
return undefined
|
||||
}
|
||||
return current
|
||||
}
|
||||
|
||||
main().catch(handleError)
|
||||
if (require.main === module) main().catch(handleError)
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
/*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
import {getOctokit} from '@actions/github';
|
||||
import type {PullRequestEditedEvent, PullRequestOpenedEvent} from '@octokit/webhooks-types';
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {syncDocsLabel} from '../bin/follow-up-docs-issue';
|
||||
|
||||
test('Docbot maintains only docs-required and preserves manual overrides on unrelated edits', async t => {
|
||||
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']);
|
||||
});
|
||||
@@ -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
|
||||
`<region_dir>/<file_id>/manifest.json` and its `part-<n>.samples` or
|
||||
`part-<n>.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.
|
||||
|
||||
@@ -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
|
||||
`<region_dir>/<file_id>/manifest.json` and its `part-<n>.samples` or
|
||||
`part-<n>.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 |
|
||||
| --- | --- | --- |
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
## HTTP API
|
||||
|
||||
When the server is started with a user provider, add `-u <username>:<password>` to the `curl` commands in this guide.
|
||||
|
||||
example:
|
||||
```bash
|
||||
curl --data "trace,flow=debug" 127.0.0.1:4000/debug/log_level
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
# Profiling CPU
|
||||
|
||||
## HTTP API
|
||||
When the server is started with a user provider, add `-u <username>:<password>` 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
|
||||
|
||||
@@ -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 <username>:<password>` 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 = "<username>:<password>"
|
||||
```
|
||||
|
||||
Then run the script:
|
||||
|
||||
```bash
|
||||
GREPTIME_CURL_CONFIG=/path/to/curl.conf ./dump.sh <pid>
|
||||
```
|
||||
|
||||
### Memory profiling control
|
||||
|
||||
You can control heap profiling activation using the new HTTP APIs:
|
||||
|
||||
@@ -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 = "<username>:<password>"`.
|
||||
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: $?)."
|
||||
|
||||
@@ -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`). |
|
||||
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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<TxnCapability> {
|
||||
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;
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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());
|
||||
|
||||
Vendored
+11
@@ -43,6 +43,17 @@ pub struct OperationMetrics {
|
||||
}
|
||||
|
||||
impl OperationMetrics {
|
||||
/// Measures a fallible operation, including cancellation before completion.
|
||||
pub async fn observe<T, E>(
|
||||
&self,
|
||||
operation: impl Future<Output = Result<T, E>>,
|
||||
) -> Result<T, E> {
|
||||
let guard = self.start();
|
||||
let result = operation.await;
|
||||
guard.finish(&result);
|
||||
result
|
||||
}
|
||||
|
||||
/// Starts tracking an operation and its elapsed time.
|
||||
pub(crate) fn start(&self) -> OperationGuard<'_> {
|
||||
self.started.inc();
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
// limitations under the License.
|
||||
|
||||
pub mod csv;
|
||||
pub mod decimal;
|
||||
pub mod json;
|
||||
pub mod orc;
|
||||
pub mod parquet;
|
||||
|
||||
@@ -0,0 +1,489 @@
|
||||
// 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.
|
||||
|
||||
//! Reads decimal and unsigned integer columns from the text of a csv or json file.
|
||||
//!
|
||||
//! A file reader that decodes a number into a `Float64` loses the digits a `Float64` can't
|
||||
//! hold. Arrow's own decimal decoding is wrong for some numbers in scientific notation, and its
|
||||
//! json integer decoding goes through a `Float64` for them. So the readers hand over the text
|
||||
//! of such a column and [`parse_number_columns`] parses it.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use arrow::array::{Array, ArrayRef, AsArray, Decimal128Array, UInt64Array};
|
||||
use arrow::error::ArrowError;
|
||||
use arrow::record_batch::RecordBatch;
|
||||
use arrow_schema::{DataType, Field, Schema, SchemaRef};
|
||||
use datafusion::error::DataFusionError;
|
||||
use datafusion::physical_plan::SendableRecordBatchStream;
|
||||
use datafusion::physical_plan::stream::RecordBatchStreamAdapter;
|
||||
use futures::StreamExt;
|
||||
|
||||
/// The type to parse the text of a column into.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum TextNumber {
|
||||
Decimal128 { precision: u8, scale: i8 },
|
||||
UInt64,
|
||||
}
|
||||
|
||||
impl TextNumber {
|
||||
fn data_type(&self) -> DataType {
|
||||
match self {
|
||||
TextNumber::Decimal128 { precision, scale } => DataType::Decimal128(*precision, *scale),
|
||||
TextNumber::UInt64 => DataType::UInt64,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses the string columns of `stream` that have a type in `numbers` into columns of that
|
||||
/// type. `numbers` has one entry for each column of the stream.
|
||||
///
|
||||
/// With `empty_as_null` an empty string is read as NULL, which is what an empty csv field is
|
||||
/// for a number. Without it an empty string is an error, like any other text that is not a
|
||||
/// number.
|
||||
pub fn parse_number_columns(
|
||||
stream: SendableRecordBatchStream,
|
||||
numbers: Vec<Option<TextNumber>>,
|
||||
empty_as_null: bool,
|
||||
) -> SendableRecordBatchStream {
|
||||
if numbers.iter().all(Option::is_none) {
|
||||
return stream;
|
||||
}
|
||||
|
||||
let input_schema = stream.schema();
|
||||
let fields = input_schema
|
||||
.fields()
|
||||
.iter()
|
||||
.zip(&numbers)
|
||||
.map(|(field, number)| match number {
|
||||
Some(number) => Arc::new(Field::clone(field).with_data_type(number.data_type())),
|
||||
None => field.clone(),
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let schema = Arc::new(Schema::new_with_metadata(
|
||||
fields,
|
||||
input_schema.metadata().clone(),
|
||||
));
|
||||
|
||||
let output_schema = schema.clone();
|
||||
let stream = stream.map(move |batch| {
|
||||
parse_number_batch(&batch?, &output_schema, &numbers, empty_as_null)
|
||||
.map_err(DataFusionError::from)
|
||||
});
|
||||
|
||||
Box::pin(RecordBatchStreamAdapter::new(schema, stream))
|
||||
}
|
||||
|
||||
fn parse_number_batch(
|
||||
batch: &RecordBatch,
|
||||
schema: &SchemaRef,
|
||||
numbers: &[Option<TextNumber>],
|
||||
empty_as_null: bool,
|
||||
) -> Result<RecordBatch, ArrowError> {
|
||||
let columns = batch
|
||||
.columns()
|
||||
.iter()
|
||||
.zip(numbers)
|
||||
.map(|(column, number)| match number {
|
||||
Some(number) => parse_number_array(column, *number, empty_as_null),
|
||||
None => Ok(column.clone()),
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
RecordBatch::try_new(schema.clone(), columns)
|
||||
}
|
||||
|
||||
fn parse_number_array(
|
||||
array: &ArrayRef,
|
||||
number: TextNumber,
|
||||
empty_as_null: bool,
|
||||
) -> Result<ArrayRef, ArrowError> {
|
||||
let strings = array.as_string_opt::<i32>().ok_or_else(|| {
|
||||
ArrowError::CastError(format!(
|
||||
"expected a string column to parse {} from, got {}",
|
||||
number.data_type(),
|
||||
array.data_type()
|
||||
))
|
||||
})?;
|
||||
let texts = strings
|
||||
.iter()
|
||||
.map(|text| text.filter(|text| !(empty_as_null && text.is_empty())));
|
||||
|
||||
Ok(match number {
|
||||
TextNumber::Decimal128 { precision, scale } => Arc::new(
|
||||
texts
|
||||
.map(|text| {
|
||||
text.map(|text| parse_decimal128(text, precision, scale))
|
||||
.transpose()
|
||||
})
|
||||
.collect::<Result<Decimal128Array, _>>()?
|
||||
.with_precision_and_scale(precision, scale)?,
|
||||
),
|
||||
TextNumber::UInt64 => Arc::new(
|
||||
texts
|
||||
.map(|text| text.map(parse_uint64).transpose())
|
||||
.collect::<Result<UInt64Array, _>>()?,
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
/// Parses a decimal number written in plain or scientific notation and returns its value
|
||||
/// with `scale` fractional digits, rounded half away from zero.
|
||||
///
|
||||
/// Every digit of the text is used, so the result is exact apart from that rounding.
|
||||
pub fn parse_decimal128(text: &str, precision: u8, scale: i8) -> Result<i128, ArrowError> {
|
||||
let error = |kind| {
|
||||
ArrowError::ParseError(match kind {
|
||||
ErrorKind::Invalid => {
|
||||
format!("can't parse the value {text} as DECIMAL({precision}, {scale})")
|
||||
}
|
||||
ErrorKind::Overflow => {
|
||||
format!("the value {text} is out of range for DECIMAL({precision}, {scale})")
|
||||
}
|
||||
})
|
||||
};
|
||||
|
||||
let (negative, value) = parse_digits(text, precision, scale, true).map_err(error)?;
|
||||
Ok(if negative { -value } else { value })
|
||||
}
|
||||
|
||||
/// Parses an unsigned integer written in plain or scientific notation.
|
||||
///
|
||||
/// Every digit of the text is used. Fractional digits are dropped, which is what Arrow's json
|
||||
/// reader does with them.
|
||||
pub fn parse_uint64(text: &str) -> Result<u64, ArrowError> {
|
||||
let error = |kind| {
|
||||
ArrowError::ParseError(match kind {
|
||||
ErrorKind::Invalid => format!("can't parse the value {text} as UInt64"),
|
||||
ErrorKind::Overflow => format!("the value {text} is out of range for UInt64"),
|
||||
})
|
||||
};
|
||||
|
||||
// A `u64` has at most 20 digits.
|
||||
let (negative, value) = parse_digits(text, 20, 0, false).map_err(error)?;
|
||||
if negative && value != 0 {
|
||||
return Err(error(ErrorKind::Overflow));
|
||||
}
|
||||
u64::try_from(value).map_err(|_| error(ErrorKind::Overflow))
|
||||
}
|
||||
|
||||
enum ErrorKind {
|
||||
Invalid,
|
||||
Overflow,
|
||||
}
|
||||
|
||||
/// Returns the sign of the number in `text` and the first `precision` digits at most of
|
||||
/// `|number| * 10^scale`. The digits after those are rounded half away from zero with `round`
|
||||
/// and dropped without it.
|
||||
fn parse_digits(
|
||||
text: &str,
|
||||
precision: u8,
|
||||
scale: i8,
|
||||
round: bool,
|
||||
) -> Result<(bool, i128), ErrorKind> {
|
||||
let (negative, number) = match text.as_bytes().first() {
|
||||
Some(b'-') => (true, &text[1..]),
|
||||
Some(b'+') => (false, &text[1..]),
|
||||
_ => (false, text),
|
||||
};
|
||||
let (mantissa, exponent) = match number.find(['e', 'E']) {
|
||||
Some(idx) => {
|
||||
let exponent = &number[idx + 1..];
|
||||
let exponent_digits = exponent.strip_prefix(['+', '-']).unwrap_or(exponent);
|
||||
if exponent_digits.is_empty() || !exponent_digits.bytes().all(|b| b.is_ascii_digit()) {
|
||||
return Err(ErrorKind::Invalid);
|
||||
}
|
||||
// An exponent that doesn't fit is far outside the range of any number here.
|
||||
let exponent = exponent
|
||||
.parse::<i64>()
|
||||
.unwrap_or(if exponent.starts_with('-') {
|
||||
i64::MIN / 2
|
||||
} else {
|
||||
i64::MAX / 2
|
||||
});
|
||||
(&number[..idx], exponent.clamp(i64::MIN / 2, i64::MAX / 2))
|
||||
}
|
||||
None => (number, 0),
|
||||
};
|
||||
let (integer, fraction) = mantissa.split_once('.').unwrap_or((mantissa, ""));
|
||||
if (integer.is_empty() && fraction.is_empty())
|
||||
|| !integer
|
||||
.bytes()
|
||||
.chain(fraction.bytes())
|
||||
.all(|b| b.is_ascii_digit())
|
||||
{
|
||||
return Err(ErrorKind::Invalid);
|
||||
}
|
||||
|
||||
// The value is `0.d1 d2 d3 ... * 10^point`, where the digits start at the first non-zero
|
||||
// one. The first `kept` digits make the integer part of `value * 10^scale`.
|
||||
let leading_zeros = integer
|
||||
.bytes()
|
||||
.chain(fraction.bytes())
|
||||
.take_while(|b| *b == b'0')
|
||||
.count();
|
||||
let mut digits = integer.bytes().chain(fraction.bytes()).skip(leading_zeros);
|
||||
let point = integer.len() as i64 - leading_zeros as i64 + exponent;
|
||||
let kept = point + scale as i64;
|
||||
|
||||
let mut value = 0_i128;
|
||||
let mut taken = 0_i64;
|
||||
while taken < kept {
|
||||
let digit = match digits.next() {
|
||||
Some(digit) => digit - b'0',
|
||||
// The digits ran out before the decimal point.
|
||||
None if value == 0 => break,
|
||||
None => 0,
|
||||
};
|
||||
if taken >= precision as i64 {
|
||||
return Err(ErrorKind::Overflow);
|
||||
}
|
||||
value = value * 10 + digit as i128;
|
||||
taken += 1;
|
||||
}
|
||||
if round && taken == kept && digits.next().is_some_and(|digit| digit >= b'5') {
|
||||
value += 1;
|
||||
if value >= 10_i128.pow(precision as u32) {
|
||||
return Err(ErrorKind::Overflow);
|
||||
}
|
||||
}
|
||||
|
||||
Ok((negative, value))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use arrow::array::StringArray;
|
||||
use arrow::datatypes::{Decimal128Type, UInt64Type};
|
||||
use datafusion::physical_plan::common::collect;
|
||||
use futures::stream;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_parse_decimal128() {
|
||||
let cases: &[(&str, u8, i8, i128)] = &[
|
||||
// Plain notation keeps every digit.
|
||||
("123456789012345678.12", 20, 2, 12345678901234567812),
|
||||
(
|
||||
"-9999999999999999999999999999.9999999999",
|
||||
38,
|
||||
10,
|
||||
-99999999999999999999999999999999999999,
|
||||
),
|
||||
("7", 20, 2, 700),
|
||||
("0", 5, 2, 0),
|
||||
("+1.5", 5, 2, 150),
|
||||
(".5", 5, 2, 50),
|
||||
("5.", 5, 2, 500),
|
||||
("000123.4500", 5, 2, 12345),
|
||||
// More fractional digits than the scale are rounded half away from zero.
|
||||
("1.005", 20, 2, 101),
|
||||
("-1.005", 20, 2, -101),
|
||||
("1.004", 20, 2, 100),
|
||||
("2.999", 20, 2, 300),
|
||||
("0.005", 5, 2, 1),
|
||||
("0.0049", 5, 2, 0),
|
||||
("-0.0049", 5, 2, 0),
|
||||
("999.994", 5, 2, 99999),
|
||||
("0.5", 3, 0, 1),
|
||||
("-2.5", 3, 0, -3),
|
||||
// Scientific notation.
|
||||
("1.2500000000000000000000000000000000000000e0", 38, 2, 125),
|
||||
("0e0", 38, 2, 0),
|
||||
("0.0e0", 5, 2, 0),
|
||||
("1e2", 20, 2, 10000),
|
||||
("1.5e-1", 20, 2, 15),
|
||||
("1.25E+1", 20, 2, 1250),
|
||||
("12345e-3", 20, 2, 1235),
|
||||
("0.00012345e5", 5, 2, 1235),
|
||||
("5e-3", 20, 2, 1),
|
||||
("4.9e-3", 20, 2, 0),
|
||||
("1e37", 38, 0, 10_i128.pow(37)),
|
||||
("1e-999999999999999999999", 20, 2, 0),
|
||||
("0e999999999999999999999", 20, 2, 0),
|
||||
// A negative scale.
|
||||
("150", 3, -1, 15),
|
||||
("144", 3, -1, 14),
|
||||
];
|
||||
for (text, precision, scale, expected) in cases {
|
||||
assert_eq!(
|
||||
parse_decimal128(text, *precision, *scale).unwrap(),
|
||||
*expected,
|
||||
"{text} as DECIMAL({precision}, {scale})"
|
||||
);
|
||||
}
|
||||
|
||||
for text in [
|
||||
// Out of range, also after rounding.
|
||||
"1000",
|
||||
"1e3",
|
||||
"999.995",
|
||||
"1e999999999999999999999",
|
||||
// Not a number.
|
||||
"",
|
||||
"-",
|
||||
".",
|
||||
"e5",
|
||||
"1e",
|
||||
"1e+",
|
||||
"1e1.5",
|
||||
"1.2.3",
|
||||
"1,5",
|
||||
" 1",
|
||||
"--1",
|
||||
"NaN",
|
||||
"inf",
|
||||
] {
|
||||
assert!(
|
||||
parse_decimal128(text, 5, 2).is_err(),
|
||||
"{text} as DECIMAL(5, 2)"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_uint64() {
|
||||
let cases: &[(&str, u64)] = &[
|
||||
("0", 0),
|
||||
("7", 7),
|
||||
("+7", 7),
|
||||
("18446744073709551615", u64::MAX),
|
||||
// A `Float64` can't hold these.
|
||||
("9007199254740993e0", 9007199254740993),
|
||||
("9007199254740993.0", 9007199254740993),
|
||||
("1.8446744073709551615e19", u64::MAX),
|
||||
("184467440737095516150e-1", u64::MAX),
|
||||
("1e3", 1000),
|
||||
("0e0", 0),
|
||||
// Fractional digits are dropped.
|
||||
("1.5", 1),
|
||||
("1.999", 1),
|
||||
("15e-1", 1),
|
||||
("0.9", 0),
|
||||
("-0", 0),
|
||||
("-0.9", 0),
|
||||
("1e-999999999999999999999", 0),
|
||||
];
|
||||
for (text, expected) in cases {
|
||||
assert_eq!(parse_uint64(text).unwrap(), *expected, "{text}");
|
||||
}
|
||||
|
||||
for text in [
|
||||
"18446744073709551616",
|
||||
"1.8446744073709551616e19",
|
||||
"1e20",
|
||||
"1e999999999999999999999",
|
||||
"-1",
|
||||
"-1.5",
|
||||
"",
|
||||
"-",
|
||||
"1e",
|
||||
"1,5",
|
||||
" 1",
|
||||
"NaN",
|
||||
] {
|
||||
assert!(parse_uint64(text).is_err(), "{text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_parse_number_columns() {
|
||||
let schema = Arc::new(Schema::new(vec![
|
||||
Field::new("k", DataType::Utf8, true),
|
||||
Field::new("price", DataType::Utf8, true),
|
||||
Field::new("id", DataType::Utf8, true),
|
||||
]));
|
||||
let batch = RecordBatch::try_new(
|
||||
schema.clone(),
|
||||
vec![
|
||||
Arc::new(StringArray::from(vec!["a", "b", "c", "d"])),
|
||||
Arc::new(StringArray::from(vec![
|
||||
Some("1.2500000000000000000000000000000000000000e0"),
|
||||
Some(""),
|
||||
None,
|
||||
Some("-0.005"),
|
||||
])),
|
||||
Arc::new(StringArray::from(vec![
|
||||
Some("9007199254740993e0"),
|
||||
Some(""),
|
||||
None,
|
||||
Some("18446744073709551615"),
|
||||
])),
|
||||
],
|
||||
)
|
||||
.unwrap();
|
||||
let stream = Box::pin(RecordBatchStreamAdapter::new(
|
||||
schema.clone(),
|
||||
stream::iter(vec![Ok(batch.clone())]),
|
||||
));
|
||||
|
||||
let price = TextNumber::Decimal128 {
|
||||
precision: 38,
|
||||
scale: 2,
|
||||
};
|
||||
let numbers = vec![None, Some(price), Some(TextNumber::UInt64)];
|
||||
let stream = parse_number_columns(stream, numbers.clone(), true);
|
||||
let stream_schema = stream.schema();
|
||||
assert_eq!(
|
||||
stream_schema.field(1),
|
||||
&Field::new("price", DataType::Decimal128(38, 2), true)
|
||||
);
|
||||
let batches = collect(stream).await.unwrap();
|
||||
assert_eq!(batches.len(), 1);
|
||||
assert_eq!(batches[0].column(0), batch.column(0));
|
||||
let prices = batches[0].column(1).as_primitive::<Decimal128Type>();
|
||||
assert_eq!(
|
||||
prices.iter().collect::<Vec<_>>(),
|
||||
vec![Some(125), None, None, Some(-1)]
|
||||
);
|
||||
assert_eq!(
|
||||
stream_schema.field(2),
|
||||
&Field::new("id", DataType::UInt64, true)
|
||||
);
|
||||
let ids = batches[0].column(2).as_primitive::<UInt64Type>();
|
||||
assert_eq!(
|
||||
ids.iter().collect::<Vec<_>>(),
|
||||
vec![Some(9007199254740993), None, None, Some(u64::MAX)]
|
||||
);
|
||||
|
||||
// An empty string is only NULL when the caller asks for it.
|
||||
let stream = Box::pin(RecordBatchStreamAdapter::new(
|
||||
schema.clone(),
|
||||
stream::iter(vec![Ok(batch.clone())]),
|
||||
));
|
||||
let error = collect(parse_number_columns(stream, numbers, false))
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("can't parse the value as DECIMAL(38, 2)"),
|
||||
"{error}"
|
||||
);
|
||||
|
||||
let stream = Box::pin(RecordBatchStreamAdapter::new(
|
||||
schema,
|
||||
stream::iter(vec![Ok(batch)]),
|
||||
));
|
||||
let stream = parse_number_columns(stream, vec![Some(price), None, None], true);
|
||||
let error = collect(stream).await.unwrap_err();
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("can't parse the value a as DECIMAL(38, 2)"),
|
||||
"{error}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -13,18 +13,24 @@
|
||||
// limitations under the License.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::io::BufReader;
|
||||
use std::io::{self, BufReader};
|
||||
use std::str::FromStr;
|
||||
use std::task::Poll;
|
||||
|
||||
use arrow::error::ArrowError;
|
||||
use arrow::json;
|
||||
use arrow::json::WriterBuilder;
|
||||
use arrow::json::reader::{ValueIter, infer_json_schema_from_iterator};
|
||||
use arrow::json::writer::LineDelimited;
|
||||
use arrow::record_batch::RecordBatch;
|
||||
use arrow_schema::Schema;
|
||||
use arrow_schema::{Schema, SchemaRef};
|
||||
use async_trait::async_trait;
|
||||
use bytes::{Buf, Bytes};
|
||||
use common_runtime;
|
||||
use datafusion::physical_plan::SendableRecordBatchStream;
|
||||
use datafusion::physical_plan::stream::RecordBatchStreamAdapter;
|
||||
use futures::StreamExt;
|
||||
use futures::stream::BoxStream;
|
||||
use object_store::ObjectStore;
|
||||
use snafu::ResultExt;
|
||||
use tokio_util::compat::FuturesAsyncReadCompatExt;
|
||||
@@ -120,6 +126,87 @@ impl FileFormat for JsonFormat {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a stream of the json file at `path` that reads the fields of `schema`.
|
||||
///
|
||||
/// Unlike the stream of a `JsonSource`, a string column also takes a number or a boolean, as
|
||||
/// the text it has in the file. So a column whose numbers must be parsed from every digit can
|
||||
/// be read as a string, see [`parse_number_columns`](super::decimal::parse_number_columns).
|
||||
pub async fn json_text_stream(
|
||||
store: &ObjectStore,
|
||||
path: &str,
|
||||
schema: SchemaRef,
|
||||
format: &JsonFormat,
|
||||
batch_size: usize,
|
||||
) -> Result<SendableRecordBatchStream> {
|
||||
let meta = store
|
||||
.stat(path)
|
||||
.await
|
||||
.context(error::ReadObjectSnafu { path })?;
|
||||
|
||||
let reader = store
|
||||
.reader(path)
|
||||
.await
|
||||
.context(error::ReadObjectSnafu { path })?
|
||||
.into_bytes_stream(0..meta.content_length())
|
||||
.await
|
||||
.context(error::ReadObjectSnafu { path })?;
|
||||
|
||||
let reader = format.compression_type.convert_stream(reader).boxed();
|
||||
json_text_stream_from_reader(reader, schema, batch_size)
|
||||
}
|
||||
|
||||
fn json_text_stream_from_reader(
|
||||
reader: BoxStream<'static, io::Result<Bytes>>,
|
||||
schema: SchemaRef,
|
||||
batch_size: usize,
|
||||
) -> Result<SendableRecordBatchStream> {
|
||||
let mut builder = Some(
|
||||
json::ReaderBuilder::new(schema.clone())
|
||||
.with_coerce_primitive(true)
|
||||
.with_batch_size(batch_size),
|
||||
);
|
||||
let mut decoder = None;
|
||||
|
||||
let mut upstream = reader.fuse();
|
||||
let mut buffered = Bytes::new();
|
||||
let mut input_finished = false;
|
||||
let stream = futures::stream::poll_fn(move |cx| {
|
||||
if let Some(builder) = builder.take() {
|
||||
decoder = Some(builder.build_decoder()?);
|
||||
}
|
||||
let Some(decoder) = decoder.as_mut() else {
|
||||
return Poll::Ready(None);
|
||||
};
|
||||
|
||||
loop {
|
||||
if input_finished {
|
||||
return Poll::Ready(decoder.flush().transpose());
|
||||
}
|
||||
|
||||
if buffered.is_empty() {
|
||||
match futures::ready!(upstream.poll_next_unpin(cx)) {
|
||||
Some(Ok(bytes)) => buffered = bytes,
|
||||
Some(Err(error)) => return Poll::Ready(Some(Err(error.into()))),
|
||||
None => input_finished = true,
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
let decoded = decoder.decode(buffered.as_ref())?;
|
||||
buffered.advance(decoded);
|
||||
// The decoder stops before the end of the input once it holds a full batch.
|
||||
if !buffered.is_empty()
|
||||
&& let Some(batch) = decoder.flush()?
|
||||
{
|
||||
return Poll::Ready(Some(Ok(batch)));
|
||||
}
|
||||
}
|
||||
})
|
||||
.map(|result: std::result::Result<RecordBatch, ArrowError>| result.map_err(Into::into));
|
||||
|
||||
Ok(Box::pin(RecordBatchStreamAdapter::new(schema, stream)))
|
||||
}
|
||||
|
||||
pub async fn stream_to_json(
|
||||
stream: SendableRecordBatchStream,
|
||||
store: ObjectStore,
|
||||
@@ -162,6 +249,7 @@ impl DfRecordBatchEncoder for json::Writer<SharedBuffer, LineDelimited> {
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
use arrow::array::AsArray;
|
||||
use common_recordbatch::adapter::DfRecordBatchStreamAdapter;
|
||||
use common_recordbatch::{RecordBatch, RecordBatches};
|
||||
use common_test_util::find_workspace_path;
|
||||
@@ -183,6 +271,72 @@ mod tests {
|
||||
.to_string()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_json_text_stream() {
|
||||
let schema = Arc::new(arrow_schema::Schema::new(vec![
|
||||
arrow_schema::Field::new("price", arrow_schema::DataType::Utf8, true),
|
||||
arrow_schema::Field::new("k", arrow_schema::DataType::Utf8, true),
|
||||
arrow_schema::Field::new("n", arrow_schema::DataType::Int64, true),
|
||||
]));
|
||||
let input: &[u8] = br#"{"k":"a","price":1.2500000000000000000000000000000000000000e0,"n":1}
|
||||
{"k":"b","price":0e0,"n":2,"unknown":true}
|
||||
{"k":"c","price":null}
|
||||
{"n":4,"price":123456789012345678.12,"k":"d"}
|
||||
{"k":"e","price":"5"}"#;
|
||||
|
||||
// Every size of input chunk and of batch gives the same rows.
|
||||
for chunk_size in [1, 7, input.len()] {
|
||||
for batch_size in [1, 2, 8192] {
|
||||
let chunks = input
|
||||
.chunks(chunk_size)
|
||||
.map(|chunk| Ok(Bytes::copy_from_slice(chunk)))
|
||||
.collect::<Vec<_>>();
|
||||
let stream = json_text_stream_from_reader(
|
||||
futures::stream::iter(chunks).boxed(),
|
||||
schema.clone(),
|
||||
batch_size,
|
||||
)
|
||||
.unwrap();
|
||||
let batches = stream.try_collect::<Vec<_>>().await.unwrap();
|
||||
assert!(batches.iter().all(|batch| batch.num_rows() <= batch_size));
|
||||
let batch = arrow::compute::concat_batches(&schema, &batches).unwrap();
|
||||
|
||||
let prices = batch.column(0).as_string::<i32>();
|
||||
assert_eq!(
|
||||
prices.iter().collect::<Vec<_>>(),
|
||||
vec![
|
||||
Some("1.2500000000000000000000000000000000000000e0"),
|
||||
Some("0e0"),
|
||||
None,
|
||||
Some("123456789012345678.12"),
|
||||
Some("5"),
|
||||
]
|
||||
);
|
||||
let keys = batch.column(1).as_string::<i32>();
|
||||
assert_eq!(
|
||||
keys.iter().collect::<Vec<_>>(),
|
||||
vec![Some("a"), Some("b"), Some("c"), Some("d"), Some("e")]
|
||||
);
|
||||
let numbers = batch
|
||||
.column(2)
|
||||
.as_primitive::<arrow::datatypes::Int64Type>();
|
||||
assert_eq!(
|
||||
numbers.iter().collect::<Vec<_>>(),
|
||||
vec![Some(1), Some(2), None, Some(4), None]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// A record that is cut off is an error.
|
||||
let stream = json_text_stream_from_reader(
|
||||
futures::stream::iter(vec![Ok(Bytes::from_static(br#"{"k":"a","price":1"#))]).boxed(),
|
||||
schema,
|
||||
8192,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(stream.try_collect::<Vec<_>>().await.is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn infer_schema_basic() {
|
||||
let json = JsonFormat::default();
|
||||
|
||||
@@ -170,6 +170,7 @@ fn cast_to_int64(array: &ArrayRef, name: &str) -> datafusion_common::Result<Arra
|
||||
|
||||
/// Perform the INSERT string operation.
|
||||
/// pos is 1-based. If pos < 1 or pos > len(str) + 1, returns original string.
|
||||
/// if replace_len is negative or past the end of the string, replace to the end.
|
||||
fn insert_string(original: &str, pos: i64, replace_len: i64, new_str: &str) -> String {
|
||||
let char_count = original.chars().count();
|
||||
|
||||
@@ -180,13 +181,9 @@ fn insert_string(original: &str, pos: i64, replace_len: i64, new_str: &str) -> S
|
||||
|
||||
let start_idx = (pos - 1) as usize; // Convert to 0-based
|
||||
|
||||
// Calculate end index for replacement
|
||||
let replace_len = if replace_len < 0 {
|
||||
0
|
||||
} else {
|
||||
replace_len as usize
|
||||
};
|
||||
let end_idx = (start_idx + replace_len).min(char_count);
|
||||
let end_idx = usize::try_from(replace_len).map_or(char_count, |replace_len| {
|
||||
start_idx.saturating_add(replace_len).min(char_count)
|
||||
});
|
||||
|
||||
let start_byte = char_to_byte_idx(original, start_idx);
|
||||
let end_byte = char_to_byte_idx(original, end_idx);
|
||||
@@ -301,6 +298,39 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_insert_negative_replace_len() {
|
||||
let cases = [
|
||||
// INSERT('Quadratic', 3, -1, 'What') => 'QuWhat'
|
||||
(("Quadratic", 3, -1, "What"), "QuWhat"),
|
||||
// INSERT('Quadratic', 1, -1, 'What') => 'What'
|
||||
(("Quadratic", 1, -1, "What"), "What"),
|
||||
(("Quadratic", 9, -1, "What"), "QuadratiWhat"),
|
||||
];
|
||||
let function = InsertFunction::default();
|
||||
|
||||
for ((curr_str, pos, len, new_str), expected) in cases {
|
||||
let curr_str_arg = Arc::new(StringArray::from(vec![curr_str]));
|
||||
let pos_arg = Arc::new(Int64Array::from(vec![pos]));
|
||||
let len_arg = Arc::new(Int64Array::from(vec![len]));
|
||||
let new_str_arg = Arc::new(StringArray::from(vec![new_str]));
|
||||
let args = create_args(vec![curr_str_arg, pos_arg, len_arg, new_str_arg]);
|
||||
|
||||
let result = function.invoke_with_args(args).unwrap();
|
||||
|
||||
if let ColumnarValue::Array(array) = result {
|
||||
let str_array = array.as_string::<i64>();
|
||||
assert_eq!(
|
||||
str_array.value(0),
|
||||
expected,
|
||||
"INSERT({curr_str:?}, {pos}, {len}, {new_str:?}) = {expected}"
|
||||
);
|
||||
} else {
|
||||
panic!("Expected array result");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_insert_unicode() {
|
||||
let function = InsertFunction::default();
|
||||
|
||||
@@ -106,3 +106,4 @@ common-test-util.workspace = true
|
||||
common-wal = { workspace = true, features = ["testing"] }
|
||||
datatypes.workspace = true
|
||||
object-store = { workspace = true, features = ["testing"] }
|
||||
tokio = { workspace = true, features = ["test-util"] }
|
||||
|
||||
@@ -89,7 +89,7 @@ impl CreateLogicalTablesProcedure {
|
||||
let chunk_size = self
|
||||
.context
|
||||
.table_metadata_manager
|
||||
.create_logical_tables_metadata_chunk_size();
|
||||
.create_logical_tables_metadata_chunk_size()?;
|
||||
if num_tables > chunk_size {
|
||||
let chunks = remaining_tasks
|
||||
.into_iter()
|
||||
|
||||
@@ -77,7 +77,7 @@ pub(crate) async fn batch_update_table_info_values(
|
||||
table_metadata_manager: &TableMetadataManager,
|
||||
table_info_values: Vec<(DeserializedValueWithBytes<TableInfoValue>, TableInfo)>,
|
||||
) -> Result<()> {
|
||||
let chunk_size = table_metadata_manager.batch_update_table_info_value_chunk_size();
|
||||
let chunk_size = table_metadata_manager.max_txn_ops()?;
|
||||
if table_info_values.len() > chunk_size {
|
||||
let chunks = table_info_values
|
||||
.into_iter()
|
||||
|
||||
@@ -12,13 +12,18 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Authority Head v1 codec and non-retrying conditional object storage.
|
||||
//! Object-store Authority election, Head v1 codec and conditional storage.
|
||||
|
||||
mod authority;
|
||||
mod head;
|
||||
mod probe;
|
||||
mod store;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
pub use authority::{
|
||||
Authority, AuthorityMutation, AuthorityPrecondition, AuthorityStatus, FencingToken,
|
||||
TakeoverOutcome,
|
||||
};
|
||||
pub use head::{AuthorityHead, HEAD_FORMAT_VERSION, NodeIdentity};
|
||||
pub use store::{AuthorityState, HeadStore};
|
||||
|
||||
@@ -0,0 +1,489 @@
|
||||
// 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.
|
||||
|
||||
//! Object-store Authority with one writer per node and monotonic local leases.
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
mod writer;
|
||||
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
use std::time::Duration;
|
||||
|
||||
use chrono::Utc;
|
||||
use tokio::sync::{mpsc, oneshot, watch};
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio::time::{Instant, sleep_until};
|
||||
|
||||
use crate::election::object_store::authority::writer::{Request, Resignation, Writer};
|
||||
use crate::election::object_store::{AuthorityHead, AuthorityState, HeadStore, NodeIdentity};
|
||||
use crate::error::{self, Error, Result};
|
||||
|
||||
const LEASE: Duration = Duration::from_secs(10);
|
||||
const RENEW_INTERVAL: Duration = Duration::from_secs(5);
|
||||
const CLOCK_GUARD: Duration = Duration::from_secs(2);
|
||||
const GET_TIMEOUT: Duration = Duration::from_millis(500);
|
||||
const QUEUE_CAPACITY: usize = 32;
|
||||
|
||||
/// A token authorizes mutations only in its original local term.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct FencingToken {
|
||||
epoch: u64,
|
||||
}
|
||||
|
||||
impl FencingToken {
|
||||
/// The logical epoch won by the takeover.
|
||||
pub fn epoch(&self) -> u64 {
|
||||
self.epoch
|
||||
}
|
||||
}
|
||||
|
||||
/// Result of one takeover attempt.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum TakeoverOutcome {
|
||||
/// The Head PUT applied and the node can lead in this term.
|
||||
Acquired(FencingToken),
|
||||
/// The Head PUT applied after local eligibility was lost.
|
||||
AppliedButInactive,
|
||||
/// The observed Head still has a live owner.
|
||||
NotEligible,
|
||||
}
|
||||
|
||||
/// The local lifecycle of the Authority writer.
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum AuthorityStatus {
|
||||
/// Has no active local term and can attempt takeover.
|
||||
#[default]
|
||||
Follower,
|
||||
/// Holds a local term that can admit writes before its deadline.
|
||||
Leader { epoch: u64, deadline: Instant },
|
||||
/// Stops admitting new writes for the term while resignation is resolved.
|
||||
Resigning { epoch: u64, deadline: Instant },
|
||||
/// The official Head is missing and requires operator recovery.
|
||||
RecoveryRequired,
|
||||
/// Rejects new operations after shutdown begins.
|
||||
Closed,
|
||||
}
|
||||
|
||||
impl AuthorityStatus {
|
||||
fn term(self) -> Option<(u64, Instant)> {
|
||||
match self {
|
||||
Self::Leader { epoch, deadline } | Self::Resigning { epoch, deadline } => {
|
||||
Some((epoch, deadline))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Additional condition on the Head for a fenced mutation.
|
||||
#[derive(Debug, Default, Clone, Copy)]
|
||||
pub enum AuthorityPrecondition {
|
||||
/// Accepts any current Head write sequence.
|
||||
#[default]
|
||||
Any,
|
||||
/// Requires an exact match with the current Head write sequence.
|
||||
WriteSeq(u64),
|
||||
}
|
||||
|
||||
impl AuthorityPrecondition {
|
||||
fn check(self, head: &AuthorityHead) -> Result<()> {
|
||||
let actual = head.write_seq();
|
||||
if let Self::WriteSeq(expected) = self
|
||||
&& actual != expected
|
||||
{
|
||||
return error::AuthorityWriteSeqMismatchSnafu { expected, actual }.fail();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Fenced Head updates supported by Head v1.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum AuthorityMutation {
|
||||
/// Renews the current lease while preserving the owner and epoch.
|
||||
Renew,
|
||||
/// Clears the current owner while preserving the epoch.
|
||||
Resign,
|
||||
}
|
||||
|
||||
/// Node-local Authority. Share one instance and its writer across callers.
|
||||
pub struct Authority {
|
||||
inner: Arc<Inner>,
|
||||
request_tx: mpsc::Sender<Request>,
|
||||
writer_task: tokio::sync::Mutex<Option<JoinHandle<()>>>,
|
||||
}
|
||||
|
||||
impl Authority {
|
||||
/// Starts the writer with the process identity generated once at startup.
|
||||
pub fn new(store: Arc<HeadStore>, identity: NodeIdentity) -> Self {
|
||||
Self::start(
|
||||
store,
|
||||
identity,
|
||||
|| {
|
||||
let now = Utc::now();
|
||||
i128::from(now.timestamp()) * 1_000_000_000
|
||||
+ i128::from(now.timestamp_subsec_nanos())
|
||||
},
|
||||
QUEUE_CAPACITY,
|
||||
common_runtime::spawn_global,
|
||||
)
|
||||
}
|
||||
|
||||
fn start(
|
||||
store: Arc<HeadStore>,
|
||||
identity: NodeIdentity,
|
||||
wall_now_ns: impl Fn() -> i128 + Send + Sync + 'static,
|
||||
capacity: usize,
|
||||
spawn: impl FnOnce(Pin<Box<dyn Future<Output = ()> + Send>>) -> JoinHandle<()>,
|
||||
) -> Self {
|
||||
let (status_tx, _) = watch::channel(AuthorityStatus::Follower);
|
||||
let inner = Arc::new(Inner {
|
||||
store,
|
||||
identity,
|
||||
wall_now_ns: Box::new(wall_now_ns),
|
||||
control: Mutex::default(),
|
||||
status_tx,
|
||||
});
|
||||
let (request_tx, request_rx) = mpsc::channel(capacity);
|
||||
let writer_task = spawn(Box::pin(Writer::new(inner.clone(), request_rx).run()));
|
||||
Self {
|
||||
inner,
|
||||
request_tx,
|
||||
writer_task: tokio::sync::Mutex::new(Some(writer_task)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads a coherent Head and its complete metadata in a single storage operation.
|
||||
pub async fn head(&self) -> Result<AuthorityState> {
|
||||
self.inner.read(Admission::Read, None).await
|
||||
}
|
||||
|
||||
/// Returns the local state, accounting for any elapsed monotonic deadline.
|
||||
pub fn status(&self) -> AuthorityStatus {
|
||||
self.inner.update(|control, _| control.status)
|
||||
}
|
||||
|
||||
/// Attempts a single conditional takeover.
|
||||
pub async fn takeover(&self) -> Result<TakeoverOutcome> {
|
||||
let (response, result) = oneshot::channel();
|
||||
self.submit(Admission::Takeover, Request::Takeover(response))
|
||||
.await?;
|
||||
result.await.unwrap_or_else(|_| Err(closed()))
|
||||
}
|
||||
|
||||
/// Requests a fenced Head update. Success confirms its PUT.
|
||||
pub async fn mutate(
|
||||
&self,
|
||||
token: &FencingToken,
|
||||
precondition: AuthorityPrecondition,
|
||||
mutation: AuthorityMutation,
|
||||
) -> Result<()> {
|
||||
let epoch = token.epoch;
|
||||
let (response, result) = oneshot::channel();
|
||||
match (mutation, precondition) {
|
||||
(AuthorityMutation::Resign, AuthorityPrecondition::Any) => {
|
||||
self.inner.update(|control, _| {
|
||||
Admission::Renew(epoch).check(control.status)?;
|
||||
let AuthorityStatus::Leader { deadline, .. } = control.status else {
|
||||
return Err(rejected("term is inactive"));
|
||||
};
|
||||
control.status = AuthorityStatus::Resigning { epoch, deadline };
|
||||
control.resignation = Some(Resignation { epoch, response });
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
(mutation, precondition) => {
|
||||
let admission = match mutation {
|
||||
AuthorityMutation::Renew => Admission::Renew(epoch),
|
||||
AuthorityMutation::Resign => Admission::ConditionalResign(epoch),
|
||||
};
|
||||
self.submit(
|
||||
admission,
|
||||
Request::Mutate {
|
||||
epoch,
|
||||
mutation,
|
||||
precondition,
|
||||
response,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
result.await.unwrap_or_else(|_| Err(closed()))
|
||||
}
|
||||
|
||||
/// Stops term admission and attempts to clear the owner before the frozen deadline.
|
||||
pub async fn resign(&self, token: &FencingToken) -> Result<()> {
|
||||
self.mutate(token, AuthorityPrecondition::Any, AuthorityMutation::Resign)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Stops the local term, cancels I/O waits and joins the writer.
|
||||
pub async fn shutdown(&self) {
|
||||
self.inner.close();
|
||||
let mut writer_task = self.writer_task.lock().await;
|
||||
if let Some(task) = writer_task.as_mut()
|
||||
&& let Err(error) = task.await
|
||||
{
|
||||
common_telemetry::warn!("Authority writer exited with error: {error}");
|
||||
}
|
||||
writer_task.take();
|
||||
}
|
||||
|
||||
async fn submit(&self, admission: Admission, request: Request) -> Result<()> {
|
||||
admission.check(self.status())?;
|
||||
tokio::select! {
|
||||
permit = self.request_tx.reserve() => {
|
||||
let permit = permit.map_err(|_| closed())?;
|
||||
self.inner.update(|control, _| {
|
||||
admission.check(control.status)?;
|
||||
permit.send(request);
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
_ = self.inner.wait_until(|status| admission.check(status).is_err()) => {
|
||||
admission.check(self.status()).and_then(|()| Err(rejected("admission changed")))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Authority {
|
||||
fn drop(&mut self) {
|
||||
self.inner.close();
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Admission {
|
||||
Read,
|
||||
Takeover,
|
||||
Renew(u64),
|
||||
ConditionalResign(u64),
|
||||
Resign(u64),
|
||||
}
|
||||
|
||||
impl Admission {
|
||||
fn check(self, status: AuthorityStatus) -> Result<()> {
|
||||
match (self, status) {
|
||||
(_, AuthorityStatus::Closed) => Err(closed()),
|
||||
(_, AuthorityStatus::RecoveryRequired) => error::AuthorityRecoveryRequiredSnafu.fail(),
|
||||
(Self::Read, _) | (Self::Takeover, AuthorityStatus::Follower) => Ok(()),
|
||||
(
|
||||
Self::Renew(expected) | Self::ConditionalResign(expected),
|
||||
AuthorityStatus::Leader { epoch, .. },
|
||||
)
|
||||
| (Self::Resign(expected), AuthorityStatus::Resigning { epoch, .. })
|
||||
if expected == epoch =>
|
||||
{
|
||||
Ok(())
|
||||
}
|
||||
_ => Err(rejected(
|
||||
"local state or fencing token does not authorize the operation",
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Control {
|
||||
status: AuthorityStatus,
|
||||
resignation: Option<Resignation>,
|
||||
snapshot: Option<SnapshotFloor>,
|
||||
}
|
||||
|
||||
impl Control {
|
||||
fn expire(&mut self, now: Instant) {
|
||||
if self
|
||||
.status
|
||||
.term()
|
||||
.is_some_and(|(_, deadline)| now >= deadline)
|
||||
{
|
||||
self.status = AuthorityStatus::Follower;
|
||||
}
|
||||
}
|
||||
|
||||
fn retire(&mut self, epoch: u64) {
|
||||
if self
|
||||
.status
|
||||
.term()
|
||||
.is_some_and(|(current, _)| current == epoch)
|
||||
{
|
||||
self.status = AuthorityStatus::Follower;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A confirmed PUT no longer has usable Metadata. Its base is retained solely
|
||||
/// to rule out a stale conditional version when the next snapshot arrives.
|
||||
enum SnapshotFloor {
|
||||
Observed(AuthorityState),
|
||||
Applied {
|
||||
head: AuthorityHead,
|
||||
base: AuthorityState,
|
||||
},
|
||||
}
|
||||
|
||||
impl SnapshotFloor {
|
||||
fn head(&self) -> &AuthorityHead {
|
||||
match self {
|
||||
Self::Observed(state) => state.head(),
|
||||
Self::Applied { head, .. } => head,
|
||||
}
|
||||
}
|
||||
|
||||
fn validate(&self, store: &HeadStore, state: &AuthorityState) -> Result<()> {
|
||||
let head = state.head();
|
||||
let floor = self.head();
|
||||
if head.epoch() < floor.epoch()
|
||||
|| head.write_seq() < floor.write_seq()
|
||||
|| (head.write_seq() == floor.write_seq() && head != floor)
|
||||
{
|
||||
return Err(invalid_snapshot(
|
||||
"Head moved behind an observed or applied write",
|
||||
));
|
||||
}
|
||||
let (metadata, expect_same_version) = match self {
|
||||
Self::Observed(previous) => {
|
||||
(previous.metadata(), head.write_seq() == floor.write_seq())
|
||||
}
|
||||
Self::Applied { base, .. } => (base.metadata(), false),
|
||||
};
|
||||
if store.same_version(metadata, state.metadata())? != expect_same_version {
|
||||
return Err(invalid_snapshot(
|
||||
"conditional version disagrees with Head write sequence",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct Inner {
|
||||
store: Arc<HeadStore>,
|
||||
identity: NodeIdentity,
|
||||
wall_now_ns: Box<dyn Fn() -> i128 + Send + Sync>,
|
||||
control: Mutex<Control>,
|
||||
status_tx: watch::Sender<AuthorityStatus>,
|
||||
}
|
||||
|
||||
impl Inner {
|
||||
/// Runs the short state transitions and PUT authorization under the same lock.
|
||||
fn update<T>(&self, f: impl FnOnce(&mut Control, Instant) -> T) -> T {
|
||||
let mut control = self.control.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let before = control.status;
|
||||
let now = Instant::now();
|
||||
control.expire(now);
|
||||
let result = f(&mut control, now);
|
||||
if control.status != before {
|
||||
self.status_tx.send_replace(control.status);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
async fn wait_until(&self, predicate: impl Fn(AuthorityStatus) -> bool) {
|
||||
let mut status = self.status_tx.subscribe();
|
||||
let _ = status.wait_for(|status| predicate(*status)).await;
|
||||
}
|
||||
|
||||
fn close(&self) {
|
||||
self.update(|control, _| control.status = AuthorityStatus::Closed);
|
||||
}
|
||||
|
||||
async fn read(
|
||||
&self,
|
||||
admission: Admission,
|
||||
deadline: Option<Instant>,
|
||||
) -> Result<AuthorityState> {
|
||||
self.update(|control, _| admission.check(control.status))?;
|
||||
let now = Instant::now();
|
||||
let stop = deadline.map_or(now + GET_TIMEOUT, |end| end.min(now + GET_TIMEOUT));
|
||||
if now >= stop {
|
||||
return Err(timeout("read"));
|
||||
}
|
||||
let result = tokio::select! {
|
||||
biased;
|
||||
_ = self.wait_until(|status| admission.check(status).is_err()) => {
|
||||
return self.update(|control, _| {
|
||||
admission.check(control.status)?;
|
||||
Err(rejected("read admission changed"))
|
||||
});
|
||||
}
|
||||
result = self.store.read_head() => result,
|
||||
_ = sleep_until(stop) => return Err(timeout("read")),
|
||||
};
|
||||
if matches!(result, Err(Error::AuthorityMissing { .. })) {
|
||||
self.update(|control, _| {
|
||||
if control.status != AuthorityStatus::Closed {
|
||||
control.status = AuthorityStatus::RecoveryRequired;
|
||||
}
|
||||
});
|
||||
}
|
||||
let state = result?;
|
||||
if Instant::now() >= stop {
|
||||
return Err(timeout("read"));
|
||||
}
|
||||
self.observe(admission, &state)?;
|
||||
Ok(state)
|
||||
}
|
||||
|
||||
fn observe(&self, admission: Admission, state: &AuthorityState) -> Result<()> {
|
||||
self.update(|control, _| {
|
||||
let head = state.head();
|
||||
if let Some(floor) = &control.snapshot {
|
||||
// A concurrent reader can observe a newer Head while this response
|
||||
// is in flight. Historical evidence is usable for readback, but
|
||||
// it cannot replace the floor or supply a new CAS condition.
|
||||
if matches!(admission, Admission::Read)
|
||||
&& head.write_seq() < floor.head().write_seq()
|
||||
&& head.epoch() <= floor.head().epoch()
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
floor.validate(&self.store, state)?;
|
||||
}
|
||||
if let Some((epoch, _)) = control.status.term()
|
||||
&& head.epoch() >= epoch
|
||||
&& (head.epoch() != epoch || head.owner.as_ref() != Some(&self.identity))
|
||||
{
|
||||
control.retire(epoch);
|
||||
}
|
||||
control.snapshot = Some(SnapshotFloor::Observed(state.clone()));
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
fn diagnostic_deadline(&self) -> u64 {
|
||||
let ns = (self.wall_now_ns)().saturating_add(LEASE.as_nanos() as i128);
|
||||
u64::try_from(ns / 1_000_000).unwrap_or(if ns < 0 { 0 } else { u64::MAX })
|
||||
}
|
||||
}
|
||||
|
||||
fn closed() -> Error {
|
||||
error::AuthorityClosedSnafu.build()
|
||||
}
|
||||
|
||||
fn rejected(reason: &'static str) -> Error {
|
||||
error::AuthorityRejectedSnafu { reason }.build()
|
||||
}
|
||||
|
||||
fn invalid_snapshot(reason: &'static str) -> Error {
|
||||
error::AuthorityMetadataSnafu { reason }.build()
|
||||
}
|
||||
|
||||
fn timeout(operation: &'static str) -> Error {
|
||||
error::AuthorityTimeoutSnafu { operation }.build()
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,596 @@
|
||||
// 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.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use object_store::ErrorKind;
|
||||
use snafu::{IntoError, OptionExt};
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
use tokio::time::{Instant, sleep_until};
|
||||
|
||||
use crate::election::object_store::authority::{
|
||||
Admission, AuthorityMutation, AuthorityPrecondition, AuthorityStatus, CLOCK_GUARD,
|
||||
FencingToken, Inner, LEASE, RENEW_INTERVAL, SnapshotFloor, TakeoverOutcome, closed, rejected,
|
||||
timeout,
|
||||
};
|
||||
use crate::election::object_store::{AuthorityHead, AuthorityState};
|
||||
use crate::error::{self, Error, Result};
|
||||
|
||||
const PUT_TIMEOUT: Duration = Duration::from_secs(2);
|
||||
const READBACK_RESERVE: Duration = Duration::from_secs(1);
|
||||
const INITIAL_BACKOFF: Duration = Duration::from_millis(50);
|
||||
const MAX_BACKOFF: Duration = Duration::from_millis(400);
|
||||
|
||||
pub(crate) enum Request {
|
||||
Takeover(oneshot::Sender<Result<TakeoverOutcome>>),
|
||||
Mutate {
|
||||
epoch: u64,
|
||||
mutation: AuthorityMutation,
|
||||
precondition: AuthorityPrecondition,
|
||||
response: oneshot::Sender<Result<()>>,
|
||||
},
|
||||
}
|
||||
|
||||
impl Request {
|
||||
fn reject(self, error: Error) {
|
||||
match self {
|
||||
Self::Takeover(response) => {
|
||||
let _ = response.send(Err(error));
|
||||
}
|
||||
Self::Mutate { response, .. } => {
|
||||
let _ = response.send(Err(error));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct Resignation {
|
||||
pub(crate) epoch: u64,
|
||||
pub(crate) response: oneshot::Sender<Result<()>>,
|
||||
}
|
||||
|
||||
pub(crate) struct Writer {
|
||||
inner: Arc<Inner>,
|
||||
request_rx: mpsc::Receiver<Request>,
|
||||
ambiguous_takeover: Option<AuthorityState>,
|
||||
}
|
||||
|
||||
impl Writer {
|
||||
pub(crate) fn new(inner: Arc<Inner>, request_rx: mpsc::Receiver<Request>) -> Self {
|
||||
Self {
|
||||
inner,
|
||||
request_rx,
|
||||
ambiguous_takeover: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn run(mut self) {
|
||||
let mut changes = self.inner.status_tx.subscribe();
|
||||
loop {
|
||||
let (status, resignation) = self
|
||||
.inner
|
||||
.update(|control, _| (control.status, control.resignation.take()));
|
||||
if status == AuthorityStatus::Closed {
|
||||
if let Some(request) = resignation {
|
||||
let _ = request.response.send(Err(closed()));
|
||||
}
|
||||
break;
|
||||
}
|
||||
if let Some(request) = resignation {
|
||||
self.drain_resigning(request.epoch);
|
||||
let result = self.resign(request.epoch).await;
|
||||
let _ = request.response.send(result);
|
||||
continue;
|
||||
}
|
||||
let term = match status {
|
||||
AuthorityStatus::Leader { epoch, deadline } => Some((epoch, deadline)),
|
||||
_ => None,
|
||||
};
|
||||
let deadline = term.map_or_else(Instant::now, |(_, deadline)| deadline);
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = changes.changed() => {}
|
||||
_ = sleep_until(deadline), if term.is_some() => {}
|
||||
_ = sleep_until(renew_at(deadline)), if term.is_some() => {
|
||||
if let Some((epoch, _)) = term {
|
||||
self.renew(epoch).await;
|
||||
}
|
||||
}
|
||||
request = self.request_rx.recv() => match request {
|
||||
Some(request) => self.process(request).await,
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
}
|
||||
self.request_rx.close();
|
||||
self.drain(closed);
|
||||
}
|
||||
|
||||
fn drain_resigning(&mut self, epoch: u64) {
|
||||
// Once the term retires, the FIFO can also contain a new takeover.
|
||||
while let Some(request) = self.inner.update(|control, _| {
|
||||
Admission::Resign(epoch).check(control.status).ok()?;
|
||||
self.request_rx.try_recv().ok()
|
||||
}) {
|
||||
request.reject(rejected("resignation stopped admission before PUT"));
|
||||
}
|
||||
}
|
||||
|
||||
fn drain(&mut self, error: impl Fn() -> Error) {
|
||||
while let Ok(request) = self.request_rx.try_recv() {
|
||||
request.reject(error());
|
||||
}
|
||||
}
|
||||
|
||||
async fn process(&mut self, request: Request) {
|
||||
match request {
|
||||
Request::Takeover(response) => {
|
||||
let _ = response.send(self.takeover().await);
|
||||
}
|
||||
Request::Mutate {
|
||||
epoch,
|
||||
mutation,
|
||||
precondition,
|
||||
response,
|
||||
} => {
|
||||
let result = loop {
|
||||
let put = match mutation {
|
||||
AuthorityMutation::Renew => {
|
||||
self.prepare_renewal(epoch, precondition, false).await
|
||||
}
|
||||
AuthorityMutation::Resign => {
|
||||
self.prepare_term(
|
||||
Admission::ConditionalResign(epoch),
|
||||
precondition,
|
||||
true,
|
||||
)
|
||||
.await
|
||||
}
|
||||
};
|
||||
match put {
|
||||
Ok(Some(put)) => {
|
||||
if matches!(mutation, AuthorityMutation::Resign) {
|
||||
self.drain_resigning(epoch);
|
||||
}
|
||||
break self.write(&put).await.map(|_| ());
|
||||
}
|
||||
Ok(None) => self.renew(epoch).await,
|
||||
Err(error) => break Err(error),
|
||||
}
|
||||
};
|
||||
let _ = response.send(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn takeover(&mut self) -> Result<TakeoverOutcome> {
|
||||
let base = self.inner.read(Admission::Takeover, None).await?;
|
||||
let ambiguous = if let Some(previous) = &self.ambiguous_takeover {
|
||||
self.inner
|
||||
.store
|
||||
.same_version(previous.metadata(), base.metadata())?
|
||||
} else {
|
||||
false
|
||||
};
|
||||
if !ambiguous {
|
||||
self.ambiguous_takeover = None;
|
||||
}
|
||||
|
||||
if base.head().owner.is_some() {
|
||||
let modified = base
|
||||
.metadata()
|
||||
.last_modified()
|
||||
.context(error::AuthorityMetadataSnafu {
|
||||
reason: "read returned no last_modified",
|
||||
})?
|
||||
.into_inner()
|
||||
.as_nanosecond();
|
||||
if (self.inner.wall_now_ns)() <= modified + (LEASE + CLOCK_GUARD).as_nanos() as i128 {
|
||||
return Ok(TakeoverOutcome::NotEligible);
|
||||
}
|
||||
}
|
||||
let mut next = base
|
||||
.head()
|
||||
.clone()
|
||||
.with_next_epoch()?
|
||||
.with_next_write_seq()?;
|
||||
next.owner = Some(self.inner.identity.clone());
|
||||
next.lease_deadline_ms = self.inner.diagnostic_deadline();
|
||||
let put = self.inner.update(|control, now| {
|
||||
Admission::Takeover.check(control.status)?;
|
||||
if let Some(floor) = &control.snapshot {
|
||||
floor.validate(&self.inner.store, &base)?;
|
||||
}
|
||||
Ok(Put {
|
||||
admission: Admission::Takeover,
|
||||
base,
|
||||
next,
|
||||
sent_at: now,
|
||||
deadline: now + LEASE,
|
||||
ambiguous,
|
||||
})
|
||||
})?;
|
||||
|
||||
match self.write(&put).await {
|
||||
Ok(true) => Ok(TakeoverOutcome::Acquired(FencingToken {
|
||||
epoch: put.next.epoch(),
|
||||
})),
|
||||
Ok(false) => Ok(TakeoverOutcome::AppliedButInactive),
|
||||
Err(error) => {
|
||||
if matches!(error, Error::AuthorityUnknown { .. }) {
|
||||
let base_unresolved = self.inner.update(|control, _| {
|
||||
control.snapshot.as_ref().is_none_or(|observed| {
|
||||
observed.head().write_seq() <= put.base.head().write_seq()
|
||||
})
|
||||
});
|
||||
self.ambiguous_takeover = base_unresolved.then_some(put.base);
|
||||
}
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn renew(&self, epoch: u64) {
|
||||
if let Ok(Some(put)) = self
|
||||
.prepare_renewal(epoch, AuthorityPrecondition::Any, true)
|
||||
.await
|
||||
&& let Err(error) = self.write(&put).await
|
||||
{
|
||||
common_telemetry::warn!(error; "Authority renewal of epoch {epoch} failed");
|
||||
}
|
||||
}
|
||||
|
||||
async fn prepare_renewal(
|
||||
&self,
|
||||
epoch: u64,
|
||||
precondition: AuthorityPrecondition,
|
||||
scheduled: bool,
|
||||
) -> Result<Option<Put>> {
|
||||
let admission = Admission::Renew(epoch);
|
||||
let result = self.prepare_term(admission, precondition, !scheduled).await;
|
||||
if let Err(error) = &result
|
||||
&& !matches!(error, Error::AuthorityWriteSeqMismatch { .. })
|
||||
{
|
||||
// Resignation or shutdown can take over while the preparation GET is in flight.
|
||||
let retired = self.inner.update(|control, _| {
|
||||
if admission.check(control.status).is_ok() {
|
||||
control.retire(epoch);
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
});
|
||||
if scheduled && retired {
|
||||
common_telemetry::warn!(error; "Authority renewal of epoch {epoch} failed");
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
async fn resign(&self, epoch: u64) -> Result<()> {
|
||||
let result = match self
|
||||
.prepare_term(Admission::Resign(epoch), AuthorityPrecondition::Any, false)
|
||||
.await
|
||||
{
|
||||
Ok(Some(put)) => self.write(&put).await.map(|_| ()),
|
||||
Ok(None) => Err(rejected("resignation could not be authorized")),
|
||||
Err(error) => Err(error),
|
||||
};
|
||||
self.inner.update(|control, _| control.retire(epoch));
|
||||
result
|
||||
}
|
||||
|
||||
/// An empty result keeps the FIFO request in hand while we perform a due renewal.
|
||||
async fn prepare_term(
|
||||
&self,
|
||||
admission: Admission,
|
||||
precondition: AuthorityPrecondition,
|
||||
defer_for_renewal: bool,
|
||||
) -> Result<Option<Put>> {
|
||||
let (epoch, deadline) = self.inner.update(|control, _| {
|
||||
admission.check(control.status)?;
|
||||
control
|
||||
.status
|
||||
.term()
|
||||
.ok_or_else(|| rejected("term is inactive"))
|
||||
})?;
|
||||
let read = match admission {
|
||||
Admission::Renew(_) => {
|
||||
self.read_renewal_head(admission, deadline, defer_for_renewal)
|
||||
.await
|
||||
}
|
||||
_ => self.inner.read(admission, Some(deadline)).await,
|
||||
};
|
||||
let base = match read {
|
||||
Ok(base) => base,
|
||||
Err(error) => {
|
||||
let renew_due = defer_for_renewal
|
||||
&& self.inner.update(|control, now| {
|
||||
admission.check(control.status).is_ok() && now >= renew_at(deadline)
|
||||
});
|
||||
return if renew_due { Ok(None) } else { Err(error) };
|
||||
}
|
||||
};
|
||||
let next = base.head().clone().with_next_write_seq().map(|mut next| {
|
||||
if matches!(
|
||||
admission,
|
||||
Admission::Resign(_) | Admission::ConditionalResign(_)
|
||||
) {
|
||||
next.owner = None;
|
||||
next.lease_deadline_ms = 0;
|
||||
} else {
|
||||
next.lease_deadline_ms = self.inner.diagnostic_deadline();
|
||||
}
|
||||
next
|
||||
});
|
||||
self.inner.update(|control, now| {
|
||||
admission.check(control.status)?;
|
||||
if defer_for_renewal && now >= renew_at(deadline) {
|
||||
return Ok(None);
|
||||
}
|
||||
if now + READBACK_RESERVE >= deadline {
|
||||
control.retire(epoch);
|
||||
return Err(timeout("write budget"));
|
||||
}
|
||||
if base.head().epoch() != epoch
|
||||
|| base.head().owner.as_ref() != Some(&self.inner.identity)
|
||||
{
|
||||
return Err(rejected("Head is not owned by this term"));
|
||||
}
|
||||
if let Some(floor) = &control.snapshot {
|
||||
floor.validate(&self.inner.store, &base)?;
|
||||
}
|
||||
precondition.check(base.head())?;
|
||||
let next = next?;
|
||||
let admission = if matches!(admission, Admission::ConditionalResign(_)) {
|
||||
// Close admission and authorize the CAS against this read under one lock.
|
||||
control.status = AuthorityStatus::Resigning { epoch, deadline };
|
||||
Admission::Resign(epoch)
|
||||
} else {
|
||||
admission
|
||||
};
|
||||
Ok(Some(Put {
|
||||
admission,
|
||||
base,
|
||||
next,
|
||||
sent_at: now,
|
||||
deadline,
|
||||
ambiguous: false,
|
||||
}))
|
||||
})
|
||||
}
|
||||
|
||||
async fn read_renewal_head(
|
||||
&self,
|
||||
admission: Admission,
|
||||
deadline: Instant,
|
||||
defer_for_renewal: bool,
|
||||
) -> Result<AuthorityState> {
|
||||
let prepare_deadline = deadline - READBACK_RESERVE;
|
||||
// A queued renewal yields to the scheduled renewal during read backoff.
|
||||
let retry_until = if defer_for_renewal {
|
||||
prepare_deadline.min(renew_at(deadline))
|
||||
} else {
|
||||
prepare_deadline
|
||||
};
|
||||
let mut backoff = INITIAL_BACKOFF;
|
||||
loop {
|
||||
let error = match self.inner.read(admission, Some(prepare_deadline)).await {
|
||||
Ok(head) => return Ok(head),
|
||||
Err(error) => error,
|
||||
};
|
||||
let retryable = matches!(
|
||||
error,
|
||||
Error::AuthorityTimeout {
|
||||
operation: "read",
|
||||
..
|
||||
}
|
||||
) || error.authority_storage_error().is_some_and(|source| {
|
||||
source.is_temporary()
|
||||
&& !matches!(
|
||||
source.kind(),
|
||||
ErrorKind::PermissionDenied | ErrorKind::NotFound
|
||||
)
|
||||
});
|
||||
let now = Instant::now();
|
||||
if !retryable || now >= retry_until {
|
||||
return Err(error);
|
||||
}
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = self.inner.wait_until(|status| admission.check(status).is_err()) => {}
|
||||
_ = sleep_until((now + backoff).min(retry_until)) => {}
|
||||
}
|
||||
self.inner
|
||||
.update(|control, _| admission.check(control.status))?;
|
||||
if Instant::now() >= retry_until {
|
||||
return Err(error);
|
||||
}
|
||||
backoff = (backoff * 2).min(MAX_BACKOFF);
|
||||
}
|
||||
}
|
||||
|
||||
async fn write(&self, put: &Put) -> Result<bool> {
|
||||
let response = self.send(put).await;
|
||||
match response {
|
||||
PutResponse::Applied => Ok(self.confirm(put, true)),
|
||||
PutResponse::Unsent(error) | PutResponse::Failed(error) => {
|
||||
self.retire(put);
|
||||
Err(error)
|
||||
}
|
||||
PutResponse::Conflict(error) => {
|
||||
self.retire(put);
|
||||
// Re-evaluate the observed version and term without replaying the CAS.
|
||||
let _ = self.inner.read(Admission::Read, Some(put.deadline)).await;
|
||||
Err(error)
|
||||
}
|
||||
PutResponse::Unknown(error) => {
|
||||
self.retire(put);
|
||||
if self.resolve(put).await {
|
||||
Ok(self.confirm(put, false))
|
||||
} else {
|
||||
Err(error::AuthorityUnknownSnafu.into_error(Box::new(error)))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn send(&self, put: &Put) -> PutResponse {
|
||||
let stop = (put.sent_at + PUT_TIMEOUT).min(put.deadline - READBACK_RESERVE);
|
||||
let request = async {
|
||||
if let Err(error) =
|
||||
Admission::Read.check(self.inner.update(|control, _| control.status))
|
||||
{
|
||||
return PutResponse::Unsent(error);
|
||||
}
|
||||
if Instant::now() >= stop {
|
||||
return PutResponse::Unsent(timeout("write budget"));
|
||||
}
|
||||
match self.inner.store.replace_head(&put.base, &put.next).await {
|
||||
Ok(()) => PutResponse::Applied,
|
||||
Err(error) => match error.authority_storage_error() {
|
||||
Some(storage)
|
||||
if matches!(
|
||||
storage.kind(),
|
||||
ErrorKind::ConditionNotMatch
|
||||
| ErrorKind::AlreadyExists
|
||||
| ErrorKind::Conflict
|
||||
| ErrorKind::NotFound
|
||||
) =>
|
||||
{
|
||||
PutResponse::Conflict(error)
|
||||
}
|
||||
Some(storage)
|
||||
if storage.is_temporary() || storage.kind() == ErrorKind::Unexpected =>
|
||||
{
|
||||
PutResponse::Unknown(error)
|
||||
}
|
||||
_ => PutResponse::Failed(error),
|
||||
},
|
||||
}
|
||||
};
|
||||
// A response already available when the task wakes still determines the PUT
|
||||
// result. The state transition separately checks the clock under the lock.
|
||||
tokio::select! {
|
||||
biased;
|
||||
result = request => result,
|
||||
_ = self.inner.wait_until(|status| status == AuthorityStatus::Closed) => PutResponse::Unknown(closed()),
|
||||
_ = sleep_until(stop) => PutResponse::Unknown(timeout("write")),
|
||||
}
|
||||
}
|
||||
|
||||
async fn resolve(&self, put: &Put) -> bool {
|
||||
let mut backoff = INITIAL_BACKOFF;
|
||||
while Instant::now() < put.deadline {
|
||||
match self.inner.read(Admission::Read, Some(put.deadline)).await {
|
||||
Ok(state) => {
|
||||
let advanced = self
|
||||
.inner
|
||||
.store
|
||||
.same_version(put.base.metadata(), state.metadata());
|
||||
if matches!(advanced, Ok(false))
|
||||
&& state.head().write_seq() >= put.next.write_seq()
|
||||
{
|
||||
// A later or competing write may have overwritten our evidence.
|
||||
// With an older ambiguous takeover, even an exact match is inconclusive.
|
||||
return !put.ambiguous && state.head() == &put.next;
|
||||
}
|
||||
}
|
||||
Err(
|
||||
Error::AuthorityClosed { .. }
|
||||
| Error::AuthorityMissing { .. }
|
||||
| Error::AuthorityRecoveryRequired { .. },
|
||||
) => return false,
|
||||
Err(_) => {}
|
||||
}
|
||||
let retry_at = (Instant::now() + backoff).min(put.deadline);
|
||||
tokio::select! {
|
||||
_ = self.inner.wait_until(|status| Admission::Read.check(status).is_err()) => return false,
|
||||
_ = sleep_until(retry_at) => {}
|
||||
}
|
||||
backoff = (backoff * 2).min(MAX_BACKOFF);
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn confirm(&self, put: &Put, direct: bool) -> bool {
|
||||
self.inner.update(|control, now| {
|
||||
let current = control.snapshot.as_ref().map(SnapshotFloor::head);
|
||||
let still_current = current
|
||||
.is_none_or(|head| head.write_seq() < put.next.write_seq() || head == &put.next);
|
||||
if current.is_none_or(|head| head.write_seq() < put.next.write_seq()) {
|
||||
control.snapshot = Some(SnapshotFloor::Applied {
|
||||
head: put.next.clone(),
|
||||
base: put.base.clone(),
|
||||
});
|
||||
}
|
||||
let epoch = put.next.epoch();
|
||||
if matches!(put.admission, Admission::Resign(_)) {
|
||||
control.retire(epoch);
|
||||
return false;
|
||||
}
|
||||
if still_current && now < put.deadline {
|
||||
match put.admission {
|
||||
Admission::Takeover if control.status == AuthorityStatus::Follower => {
|
||||
control.status = AuthorityStatus::Leader {
|
||||
epoch,
|
||||
deadline: put.deadline,
|
||||
};
|
||||
return true;
|
||||
}
|
||||
Admission::Renew(_)
|
||||
if direct && Admission::Renew(epoch).check(control.status).is_ok() =>
|
||||
{
|
||||
control.status = AuthorityStatus::Leader {
|
||||
epoch,
|
||||
deadline: put.sent_at + LEASE,
|
||||
};
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
false
|
||||
})
|
||||
}
|
||||
|
||||
fn retire(&self, put: &Put) {
|
||||
if let Admission::Renew(epoch) | Admission::Resign(epoch) = put.admission {
|
||||
self.inner.update(|control, _| control.retire(epoch));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn renew_at(deadline: Instant) -> Instant {
|
||||
deadline - (LEASE - RENEW_INTERVAL)
|
||||
}
|
||||
|
||||
/// The writer obtains this single-use authorization under the state lock and
|
||||
/// owns it until the PUT outcome is classified. No other code sends a Head PUT.
|
||||
struct Put {
|
||||
admission: Admission,
|
||||
base: AuthorityState,
|
||||
next: AuthorityHead,
|
||||
sent_at: Instant,
|
||||
deadline: Instant,
|
||||
ambiguous: bool,
|
||||
}
|
||||
|
||||
enum PutResponse {
|
||||
Applied,
|
||||
Unsent(Error),
|
||||
Conflict(Error),
|
||||
Failed(Error),
|
||||
Unknown(Error),
|
||||
}
|
||||
@@ -12,7 +12,7 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use common_error::ext::{ErrorExt, RetryHint};
|
||||
@@ -24,14 +24,20 @@ use object_store::layers::mock::{
|
||||
Result, RpCreateDir, RpPresign, RpRead, RpRename, RpStat, Service, Timestamp, oio,
|
||||
};
|
||||
use object_store::{ObjectStore, ServiceInfo};
|
||||
use tokio::sync::{Notify, oneshot};
|
||||
use tokio::time::Instant;
|
||||
|
||||
use super::*;
|
||||
|
||||
// Explicitly supplies coherent response metadata. This is a protocol simulator,
|
||||
// not a claim about memory-service or real-backend semantics.
|
||||
#[derive(Debug, Default)]
|
||||
struct Data {
|
||||
objects: HashMap<String, (Vec<u8>, Metadata)>,
|
||||
pub(crate) struct Data {
|
||||
pub(crate) calls: Vec<Call>,
|
||||
read_actions: VecDeque<ReadAction>,
|
||||
write_actions: VecDeque<WriteAction>,
|
||||
next_write_error: Option<Error>,
|
||||
pub(crate) objects: HashMap<String, (Vec<u8>, Metadata)>,
|
||||
seq: u64,
|
||||
writes: usize,
|
||||
ignore_conditions: bool,
|
||||
@@ -58,8 +64,8 @@ enum ConflictMutation {
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct Backend {
|
||||
data: Arc<Mutex<Data>>,
|
||||
pub(crate) struct Backend {
|
||||
pub(crate) data: Arc<Mutex<Data>>,
|
||||
scheme: &'static str,
|
||||
capability: Capability,
|
||||
}
|
||||
@@ -82,6 +88,116 @@ impl Default for Backend {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Call {
|
||||
Get(Instant),
|
||||
Put(AuthorityHead),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum ReadAction {
|
||||
Pause(DeferredRead),
|
||||
PauseResponse(DeferredRead),
|
||||
Fail(Error),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct DeferredRead {
|
||||
pub(crate) arrived: Arc<Notify>,
|
||||
pub(crate) release: Arc<Notify>,
|
||||
}
|
||||
|
||||
type WriteReceipt = (Result<Metadata>, oneshot::Sender<Result<Metadata>>);
|
||||
|
||||
#[derive(Debug)]
|
||||
struct WriteAction {
|
||||
arrived: Arc<Notify>,
|
||||
commit: oneshot::Receiver<bool>,
|
||||
committed: oneshot::Sender<WriteReceipt>,
|
||||
}
|
||||
|
||||
pub(crate) struct DeferredWrite {
|
||||
pub(crate) arrived: Arc<Notify>,
|
||||
commit: Option<oneshot::Sender<bool>>,
|
||||
committed: oneshot::Receiver<WriteReceipt>,
|
||||
receipt: Option<WriteReceipt>,
|
||||
}
|
||||
|
||||
impl DeferredWrite {
|
||||
pub(crate) async fn commit(&mut self, apply: bool) -> bool {
|
||||
self.commit.take().unwrap().send(apply).unwrap();
|
||||
let receipt = (&mut self.committed).await.unwrap();
|
||||
let applied = receipt.0.is_ok();
|
||||
self.receipt = Some(receipt);
|
||||
applied
|
||||
}
|
||||
|
||||
pub(crate) fn respond(mut self) -> bool {
|
||||
let (result, response) = self.receipt.take().unwrap();
|
||||
response.send(result).is_ok()
|
||||
}
|
||||
}
|
||||
|
||||
impl Backend {
|
||||
pub(crate) fn pause_next_read(&self) -> DeferredRead {
|
||||
self.pause_read(ReadAction::Pause)
|
||||
}
|
||||
|
||||
pub(crate) fn pause_next_read_response(&self) -> DeferredRead {
|
||||
self.pause_read(ReadAction::PauseResponse)
|
||||
}
|
||||
|
||||
fn pause_read(&self, action: impl FnOnce(DeferredRead) -> ReadAction) -> DeferredRead {
|
||||
let gate = DeferredRead {
|
||||
arrived: Arc::new(Notify::new()),
|
||||
release: Arc::new(Notify::new()),
|
||||
};
|
||||
self.data
|
||||
.lock()
|
||||
.unwrap()
|
||||
.read_actions
|
||||
.push_back(action(gate.clone()));
|
||||
gate
|
||||
}
|
||||
|
||||
pub(crate) fn fail_next_read(&self) {
|
||||
self.fail_next_read_with(denied());
|
||||
}
|
||||
|
||||
pub(crate) fn fail_next_read_with(&self, error: Error) {
|
||||
self.data
|
||||
.lock()
|
||||
.unwrap()
|
||||
.read_actions
|
||||
.push_back(ReadAction::Fail(error));
|
||||
}
|
||||
|
||||
pub(crate) fn fail_next_write(&self, error: Error) {
|
||||
self.data.lock().unwrap().next_write_error = Some(error);
|
||||
}
|
||||
|
||||
pub(crate) fn defer_next_write(&self) -> DeferredWrite {
|
||||
let arrived = Arc::new(Notify::new());
|
||||
let (commit_tx, commit) = oneshot::channel();
|
||||
let (committed, committed_rx) = oneshot::channel();
|
||||
self.data
|
||||
.lock()
|
||||
.unwrap()
|
||||
.write_actions
|
||||
.push_back(WriteAction {
|
||||
arrived: arrived.clone(),
|
||||
commit,
|
||||
committed,
|
||||
});
|
||||
DeferredWrite {
|
||||
arrived,
|
||||
commit: Some(commit_tx),
|
||||
committed: committed_rx,
|
||||
receipt: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Service for Backend {
|
||||
async fn create_dir(
|
||||
&self,
|
||||
@@ -157,7 +273,7 @@ impl Service for Backend {
|
||||
}
|
||||
}
|
||||
|
||||
struct TestLister;
|
||||
pub(crate) struct TestLister;
|
||||
|
||||
impl oio::List for TestLister {
|
||||
async fn next(&mut self) -> Result<Option<oio::Entry>> {
|
||||
@@ -169,13 +285,28 @@ fn denied() -> Error {
|
||||
Error::new(ErrorKind::PermissionDenied, "injected permission failure")
|
||||
}
|
||||
|
||||
struct TestReader {
|
||||
pub(crate) struct TestReader {
|
||||
data: Arc<Mutex<Data>>,
|
||||
path: String,
|
||||
}
|
||||
|
||||
impl oio::Read for TestReader {
|
||||
async fn open(&self, _: BytesRange) -> Result<(RpRead, Box<dyn oio::ReadStreamDyn>)> {
|
||||
let action = {
|
||||
let mut data = self.data.lock().unwrap();
|
||||
data.calls.push(Call::Get(Instant::now()));
|
||||
data.read_actions.pop_front()
|
||||
};
|
||||
let pause_response = match action {
|
||||
Some(ReadAction::Pause(gate)) => {
|
||||
gate.arrived.notify_one();
|
||||
gate.release.notified().await;
|
||||
None
|
||||
}
|
||||
Some(ReadAction::PauseResponse(gate)) => Some((gate.arrived, gate.release)),
|
||||
Some(ReadAction::Fail(error)) => return Err(error),
|
||||
None => None,
|
||||
};
|
||||
let data = self.data.lock().unwrap();
|
||||
let (body, meta) = data
|
||||
.objects
|
||||
@@ -190,7 +321,7 @@ impl oio::Read for TestReader {
|
||||
rp,
|
||||
Box::new(TestStream {
|
||||
body: Buffer::from(body.clone()),
|
||||
pause: data.pause.clone(),
|
||||
pause: pause_response.or_else(|| data.pause.clone()),
|
||||
}),
|
||||
))
|
||||
}
|
||||
@@ -215,7 +346,8 @@ impl oio::ReadStream for TestStream {
|
||||
}
|
||||
}
|
||||
|
||||
struct TestWriter {
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct TestWriter {
|
||||
data: Arc<Mutex<Data>>,
|
||||
path: String,
|
||||
args: OpWrite,
|
||||
@@ -242,11 +374,47 @@ impl oio::Write for TestWriter {
|
||||
if let Some(barrier) = barrier {
|
||||
barrier.wait().await;
|
||||
}
|
||||
let action = {
|
||||
let mut data = self.data.lock().unwrap();
|
||||
if data.write_barrier.is_some() {
|
||||
data.writes_in_flight -= 1;
|
||||
}
|
||||
data.writes += 1;
|
||||
data.calls
|
||||
.push(Call::Put(AuthorityHead::decode(&self.body).unwrap()));
|
||||
data.write_actions.pop_front()
|
||||
};
|
||||
if let Some(action) = action {
|
||||
let writer = self.clone();
|
||||
let (response, result) = oneshot::channel();
|
||||
// The server owns the conditional update even after the client stops waiting.
|
||||
tokio::spawn(async move {
|
||||
action.arrived.notify_one();
|
||||
let outcome = match action.commit.await {
|
||||
Ok(true) => writer.commit(),
|
||||
Ok(false) => Err(denied()),
|
||||
Err(_) => return,
|
||||
};
|
||||
let _ = action.committed.send((outcome, response));
|
||||
});
|
||||
return result.await.unwrap_or_else(|_| {
|
||||
Err(Error::new(ErrorKind::Unexpected, "lost response").set_temporary())
|
||||
});
|
||||
}
|
||||
self.commit()
|
||||
}
|
||||
|
||||
async fn abort(&mut self) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TestWriter {
|
||||
fn commit(&self) -> Result<Metadata> {
|
||||
let mut data = self.data.lock().unwrap();
|
||||
if data.write_barrier.is_some() {
|
||||
data.writes_in_flight -= 1;
|
||||
if let Some(error) = data.next_write_error.take() {
|
||||
return Err(error);
|
||||
}
|
||||
data.writes += 1;
|
||||
if data.fail == Some("write") {
|
||||
return Err(Error::new(ErrorKind::Unexpected, "lost response").set_temporary());
|
||||
}
|
||||
@@ -300,10 +468,6 @@ impl oio::Write for TestWriter {
|
||||
.insert(self.path.clone(), (self.body.clone(), meta.clone()));
|
||||
Ok(meta)
|
||||
}
|
||||
|
||||
async fn abort(&mut self) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn corrupt_conflict(data: &mut Data, path: &str, mutation: Option<ConflictMutation>) {
|
||||
@@ -326,7 +490,7 @@ fn corrupt_conflict(data: &mut Data, path: &str, mutation: Option<ConflictMutati
|
||||
data.corruptions += 1;
|
||||
}
|
||||
|
||||
struct TestDeleter(Arc<Mutex<Data>>);
|
||||
pub(crate) struct TestDeleter(Arc<Mutex<Data>>);
|
||||
|
||||
impl oio::Delete for TestDeleter {
|
||||
async fn delete(&mut self, path: &str, _: OpDelete) -> Result<()> {
|
||||
@@ -344,7 +508,7 @@ impl oio::Delete for TestDeleter {
|
||||
}
|
||||
}
|
||||
|
||||
fn store(backend: &Backend) -> HeadStore {
|
||||
pub(crate) fn store(backend: &Backend) -> HeadStore {
|
||||
HeadStore::new_for_test(
|
||||
ObjectStore::from_parts(OperationContext::default(), Arc::new(backend.clone())),
|
||||
"cluster",
|
||||
|
||||
@@ -1141,6 +1141,51 @@ pub enum Error {
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display("Authority is closed"))]
|
||||
AuthorityClosed {
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display("Authority Head requires operator recovery"))]
|
||||
AuthorityRecoveryRequired {
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display("Authority operation was not executed: {}", reason))]
|
||||
AuthorityRejected {
|
||||
reason: &'static str,
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display(
|
||||
"Authority Head write sequence mismatch: expected {}, actual {}",
|
||||
expected,
|
||||
actual
|
||||
))]
|
||||
AuthorityWriteSeqMismatch {
|
||||
expected: u64,
|
||||
actual: u64,
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display("Authority {} timed out", operation))]
|
||||
AuthorityTimeout {
|
||||
operation: &'static str,
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display("Authority PUT outcome is unknown"))]
|
||||
AuthorityUnknown {
|
||||
source: Box<Error>,
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display("Failed to open Authority storage"))]
|
||||
AuthorityOpen {
|
||||
#[snafu(source)]
|
||||
@@ -1334,7 +1379,13 @@ impl ErrorExt for Error {
|
||||
AuthorityMissing { .. }
|
||||
| AuthorityMetadata { .. }
|
||||
| AuthorityStorage { .. }
|
||||
| AuthorityOpen { .. } => StatusCode::StorageUnavailable,
|
||||
| AuthorityOpen { .. }
|
||||
| AuthorityClosed { .. }
|
||||
| AuthorityRecoveryRequired { .. }
|
||||
| AuthorityTimeout { .. }
|
||||
| AuthorityUnknown { .. } => StatusCode::StorageUnavailable,
|
||||
AuthorityRejected { .. } => StatusCode::IllegalState,
|
||||
AuthorityWriteSeqMismatch { .. } => StatusCode::RequestOutdated,
|
||||
NoLeader { .. } => StatusCode::TableUnavailable,
|
||||
ValueNotExist { .. }
|
||||
| ProcedurePoisonConflict { .. }
|
||||
@@ -1557,6 +1608,7 @@ impl Error {
|
||||
Self::AuthorityStorage { error, .. } | Self::AuthorityMissing { error, .. } => {
|
||||
Some(error)
|
||||
}
|
||||
Self::AuthorityUnknown { source, .. } => source.authority_storage_error(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1036,6 +1036,17 @@ impl Display for ApplyStagingManifest {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub enum MetadataCompaction {
|
||||
/// Wait for compaction to drain, then hold the pause for the remaining sync budget.
|
||||
Pause {
|
||||
region_id: RegionId,
|
||||
remaining: Duration,
|
||||
},
|
||||
/// Resume compaction on the source metadata region.
|
||||
Release { region_id: RegionId },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Display, PartialEq)]
|
||||
pub enum Instruction {
|
||||
/// Opens regions.
|
||||
@@ -1069,6 +1080,8 @@ pub enum Instruction {
|
||||
Suspend,
|
||||
/// Makes regions enter staging state.
|
||||
EnterStagingRegions(Vec<EnterStagingRegion>),
|
||||
/// Controls source metadata compaction during repartition.
|
||||
MetadataCompaction(MetadataCompaction),
|
||||
/// Syncs regions.
|
||||
SyncRegions(Vec<SyncRegion>),
|
||||
/// Remaps manifests for a region.
|
||||
@@ -1350,6 +1363,7 @@ pub enum InstructionReply {
|
||||
GetPackedFileRefs(GetPackedFileRefsReply),
|
||||
GcRegions(GcRegionsReply),
|
||||
EnterStagingRegions(EnterStagingRegionsReply),
|
||||
MetadataCompaction(SimpleReply),
|
||||
SyncRegions(SyncRegionsReply),
|
||||
RemapManifest(RemapManifestReply),
|
||||
ApplyStagingManifests(ApplyStagingManifestsReply),
|
||||
@@ -1379,6 +1393,9 @@ impl Display for InstructionReply {
|
||||
reply.replies
|
||||
)
|
||||
}
|
||||
Self::MetadataCompaction(reply) => {
|
||||
write!(f, "InstructionReply::MetadataCompaction({reply})")
|
||||
}
|
||||
Self::SyncRegions(reply) => {
|
||||
write!(f, "InstructionReply::SyncRegions({:?})", reply.replies)
|
||||
}
|
||||
@@ -1469,6 +1486,32 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_metadata_compaction_mailbox_wire() {
|
||||
let wire = serde_json::json!([
|
||||
{"MetadataCompaction": {"Pause": {
|
||||
"region_id": 4294967298_u64,
|
||||
"remaining": {"secs": 19, "nanos": 500000000}
|
||||
}}},
|
||||
{"MetadataCompaction": {"Release": {
|
||||
"region_id": 4294967298_u64
|
||||
}}}
|
||||
]);
|
||||
let region_id = RegionId::new(1, 2);
|
||||
let expected = vec![
|
||||
Instruction::MetadataCompaction(MetadataCompaction::Pause {
|
||||
region_id,
|
||||
remaining: Duration::from_millis(19_500),
|
||||
}),
|
||||
Instruction::MetadataCompaction(MetadataCompaction::Release { region_id }),
|
||||
];
|
||||
assert_eq!(
|
||||
expected,
|
||||
serde_json::from_value::<Vec<Instruction>>(wire.clone()).unwrap()
|
||||
);
|
||||
assert_eq!(wire, serde_json::to_value(expected).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_instruction_error_serde() {
|
||||
let error = InstructionError::new(
|
||||
|
||||
@@ -907,10 +907,10 @@ impl TableMetadataManager {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn create_logical_tables_metadata_chunk_size(&self) -> usize {
|
||||
pub fn create_logical_tables_metadata_chunk_size(&self) -> Result<usize> {
|
||||
// The batch size is max_txn_size / 3 because the size of the `tables_data`
|
||||
// is 3 times the size of the `tables_data`.
|
||||
self.kv_backend.max_txn_ops() / 3
|
||||
Ok(self.max_txn_ops()? / 3)
|
||||
}
|
||||
|
||||
/// Creates metadata for multiple logical tables and return an error if different metadata exists.
|
||||
@@ -1338,7 +1338,11 @@ impl TableMetadataManager {
|
||||
&self,
|
||||
tables: &[(TableId, TableName)],
|
||||
) -> Result<()> {
|
||||
let max_ops = self.kv_backend.max_txn_ops().max(1);
|
||||
// Without a transaction limit, delete one table's identity keys per request.
|
||||
let max_ops = self
|
||||
.kv_backend
|
||||
.txn_capability()
|
||||
.map_or(Self::TABLE_IDENTITY_KEYS, |txn| txn.max_ops.max(1));
|
||||
let tables_per_request = (max_ops / Self::TABLE_IDENTITY_KEYS).max(1);
|
||||
// Keep a table's keys together whenever they fit in one backend request. A backend
|
||||
// limit smaller than a single table still requires splitting, as with single-table drop.
|
||||
@@ -1677,8 +1681,12 @@ impl TableMetadataManager {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn batch_update_table_info_value_chunk_size(&self) -> usize {
|
||||
self.kv_backend.max_txn_ops()
|
||||
pub fn max_txn_ops(&self) -> Result<usize> {
|
||||
Ok(self
|
||||
.kv_backend
|
||||
.txn_capability()
|
||||
.context(error::UnsupportedSnafu { operation: "txn" })?
|
||||
.max_ops)
|
||||
}
|
||||
|
||||
pub async fn batch_update_table_info_values(
|
||||
@@ -3136,7 +3144,8 @@ mod tests {
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
for limit in [1, 3, 127, 128, 129] {
|
||||
for txn_limit in [None, Some(1), Some(3), Some(127), Some(128), Some(129)] {
|
||||
let limit = txn_limit.unwrap_or(TableMetadataManager::TABLE_IDENTITY_KEYS);
|
||||
let tables = (0..65)
|
||||
.map(|id| {
|
||||
(
|
||||
@@ -3152,8 +3161,11 @@ mod tests {
|
||||
.collect::<HashSet<_>>(),
|
||||
));
|
||||
let requests = Arc::new(AtomicUsize::new(0));
|
||||
let backend = MockKvBackendBuilder::default()
|
||||
.max_txn_ops(limit)
|
||||
let mut builder = MockKvBackendBuilder::default();
|
||||
if let Some(limit) = txn_limit {
|
||||
builder.max_txn_ops(limit);
|
||||
}
|
||||
let backend = builder
|
||||
.batch_delete_fn({
|
||||
let remaining = remaining.clone();
|
||||
let requests = requests.clone();
|
||||
@@ -3415,6 +3427,7 @@ mod tests {
|
||||
let range_calls = Arc::new(AtomicUsize::new(0));
|
||||
let batch_get_calls = Arc::new(AtomicUsize::new(0));
|
||||
let mock = MockKvBackend {
|
||||
capabilities: Default::default(),
|
||||
range_fn: Some({
|
||||
let all_tombstones = all_tombstones.clone();
|
||||
let range_calls = range_calls.clone();
|
||||
|
||||
@@ -16,7 +16,7 @@ use std::collections::HashMap;
|
||||
|
||||
use common_telemetry::debug;
|
||||
use futures_util::stream::BoxStream;
|
||||
use snafu::ensure;
|
||||
use snafu::{OptionExt, ensure};
|
||||
|
||||
use crate::error::{self, Result};
|
||||
use crate::key::TABLE_NAME_KEY_PREFIX;
|
||||
@@ -294,16 +294,20 @@ impl TombstoneManager {
|
||||
.fail()
|
||||
}
|
||||
|
||||
fn max_txn_ops(&self) -> usize {
|
||||
fn max_txn_ops(&self) -> Result<usize> {
|
||||
#[cfg(test)]
|
||||
if let Some(max_txn_ops) = self.max_txn_ops {
|
||||
return max_txn_ops;
|
||||
return Ok(max_txn_ops);
|
||||
}
|
||||
self.kv_backend.max_txn_ops()
|
||||
Ok(self
|
||||
.kv_backend
|
||||
.txn_capability()
|
||||
.context(error::UnsupportedSnafu { operation: "txn" })?
|
||||
.max_ops)
|
||||
}
|
||||
|
||||
async fn execute_extra_ops(&self, extra_ops: Vec<TxnOp>) -> Result<()> {
|
||||
let max_txn_ops = self.max_txn_ops();
|
||||
let max_txn_ops = self.max_txn_ops()?;
|
||||
ensure!(
|
||||
max_txn_ops > 0,
|
||||
error::UnexpectedSnafu {
|
||||
@@ -348,7 +352,7 @@ impl TombstoneManager {
|
||||
} else {
|
||||
MOVE_VALUE_TXN_OPS_PER_KEY
|
||||
};
|
||||
let max_txn_ops = self.max_txn_ops();
|
||||
let max_txn_ops = self.max_txn_ops()?;
|
||||
ensure!(
|
||||
max_txn_ops >= txn_ops_per_key,
|
||||
error::UnexpectedSnafu {
|
||||
@@ -571,7 +575,7 @@ mod tests {
|
||||
};
|
||||
use crate::kv_backend::memory::MemoryKvBackend;
|
||||
use crate::kv_backend::txn::{Txn, TxnRequest, TxnResponse};
|
||||
use crate::kv_backend::{KvBackend, TxnService};
|
||||
use crate::kv_backend::{KvBackend, TxnCapability, TxnService};
|
||||
use crate::rpc::KeyValue;
|
||||
use crate::rpc::store::{
|
||||
BatchDeleteRequest, BatchDeleteResponse, BatchGetRequest, BatchGetResponse,
|
||||
@@ -605,8 +609,10 @@ mod tests {
|
||||
self.inner.txn(txn).await
|
||||
}
|
||||
|
||||
fn max_txn_ops(&self) -> usize {
|
||||
self.max_txn_ops
|
||||
fn txn_capability(&self) -> Option<TxnCapability> {
|
||||
Some(TxnCapability {
|
||||
max_ops: self.max_txn_ops,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -655,6 +661,10 @@ mod tests {
|
||||
impl TxnService for StalePointGetKvBackend {
|
||||
type Error = Error;
|
||||
|
||||
fn txn_capability(&self) -> Option<TxnCapability> {
|
||||
self.inner.txn_capability()
|
||||
}
|
||||
|
||||
async fn txn(&self, txn: Txn) -> Result<TxnResponse> {
|
||||
self.inner.txn(txn).await
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ use std::sync::Arc;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use common_error::ext::ErrorExt;
|
||||
pub use txn::TxnService;
|
||||
pub use txn::{TxnCapability, TxnService};
|
||||
|
||||
use crate::error::Error;
|
||||
use crate::kv_backend::txn::{Txn, TxnOpResponse};
|
||||
@@ -63,11 +63,22 @@ pub const DEFAULT_META_TABLE_NAME: &str = "greptime_metakv";
|
||||
// The default lock id for election, default is 1.
|
||||
pub const DEFAULT_META_ELECTION_LOCK_ID: u64 = 1;
|
||||
|
||||
/// Guarantees provided by a key-value backend.
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct KvBackendCapabilities {
|
||||
/// All key-value pairs in one [`KvBackend::batch_put`] call are applied atomically.
|
||||
pub atomic_batch_put: bool,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait KvBackend: TxnService
|
||||
where
|
||||
Self::Error: ErrorExt,
|
||||
{
|
||||
fn capabilities(&self) -> KvBackendCapabilities {
|
||||
KvBackendCapabilities::default()
|
||||
}
|
||||
|
||||
fn name(&self) -> &str;
|
||||
|
||||
fn as_any(&self) -> &dyn Any;
|
||||
|
||||
@@ -16,7 +16,9 @@ use std::any::Any;
|
||||
|
||||
use crate::error::Error;
|
||||
use crate::kv_backend::txn::{Txn, TxnOp, TxnOpResponse, TxnResponse};
|
||||
use crate::kv_backend::{KvBackend, KvBackendRef, TxnService};
|
||||
use crate::kv_backend::{
|
||||
KvBackend, KvBackendCapabilities, KvBackendRef, TxnCapability, TxnService,
|
||||
};
|
||||
use crate::rpc::KeyValue;
|
||||
use crate::rpc::store::{
|
||||
BatchDeleteRequest, BatchDeleteResponse, BatchGetRequest, BatchGetResponse, BatchPutRequest,
|
||||
@@ -46,13 +48,17 @@ impl TxnService for ChrootKvBackend {
|
||||
Ok(self.chroot_txn_response(txn_res))
|
||||
}
|
||||
|
||||
fn max_txn_ops(&self) -> usize {
|
||||
self.inner.max_txn_ops()
|
||||
fn txn_capability(&self) -> Option<TxnCapability> {
|
||||
self.inner.txn_capability()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl KvBackend for ChrootKvBackend {
|
||||
fn capabilities(&self) -> KvBackendCapabilities {
|
||||
self.inner.capabilities()
|
||||
}
|
||||
|
||||
fn name(&self) -> &str {
|
||||
self.inner.name()
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ use snafu::{ResultExt, ensure};
|
||||
|
||||
use crate::error::{self, Error, LoadTlsCertificateSnafu, Result};
|
||||
use crate::kv_backend::txn::{Txn as KvTxn, TxnResponse as KvTxnResponse};
|
||||
use crate::kv_backend::{KvBackend, KvBackendRef, TxnService};
|
||||
use crate::kv_backend::{KvBackend, KvBackendRef, TxnCapability, TxnService};
|
||||
use crate::metrics::METRIC_META_TXN_REQUEST;
|
||||
use crate::rpc::KeyValue;
|
||||
use crate::rpc::store::{
|
||||
@@ -80,7 +80,7 @@ impl EtcdStore {
|
||||
}
|
||||
|
||||
async fn do_multi_txn(&self, txn_ops: Vec<TxnOp>) -> Result<Vec<TxnResponse>> {
|
||||
let max_txn_ops = self.max_txn_ops();
|
||||
let max_txn_ops = self.max_txn_ops;
|
||||
if txn_ops.len() < max_txn_ops {
|
||||
// fast path
|
||||
let _timer = METRIC_META_TXN_REQUEST
|
||||
@@ -285,8 +285,10 @@ impl TxnService for EtcdStore {
|
||||
txn_res.try_into()
|
||||
}
|
||||
|
||||
fn max_txn_ops(&self) -> usize {
|
||||
self.max_txn_ops
|
||||
fn txn_capability(&self) -> Option<TxnCapability> {
|
||||
Some(TxnCapability {
|
||||
max_ops: self.max_txn_ops,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -21,7 +21,9 @@ use async_trait::async_trait;
|
||||
use common_error::ext::ErrorExt;
|
||||
|
||||
use crate::kv_backend::txn::{Txn, TxnOp, TxnOpResponse, TxnRequest, TxnResponse};
|
||||
use crate::kv_backend::{KvBackend, KvBackendRef, ResettableKvBackend, TxnService};
|
||||
use crate::kv_backend::{
|
||||
KvBackend, KvBackendCapabilities, KvBackendRef, ResettableKvBackend, TxnCapability, TxnService,
|
||||
};
|
||||
use crate::metrics::METRIC_META_TXN_REQUEST;
|
||||
use crate::rpc::KeyValue;
|
||||
use crate::rpc::store::{
|
||||
@@ -76,6 +78,12 @@ impl<T> MemoryKvBackend<T> {
|
||||
|
||||
#[async_trait]
|
||||
impl<T: ErrorExt + Send + Sync + 'static> KvBackend for MemoryKvBackend<T> {
|
||||
fn capabilities(&self) -> KvBackendCapabilities {
|
||||
KvBackendCapabilities {
|
||||
atomic_batch_put: true,
|
||||
}
|
||||
}
|
||||
|
||||
fn name(&self) -> &str {
|
||||
"Memory"
|
||||
}
|
||||
@@ -286,8 +294,10 @@ impl<T: ErrorExt + Send + Sync> TxnService for MemoryKvBackend<T> {
|
||||
})
|
||||
}
|
||||
|
||||
fn max_txn_ops(&self) -> usize {
|
||||
usize::MAX
|
||||
fn txn_capability(&self) -> Option<TxnCapability> {
|
||||
Some(TxnCapability {
|
||||
max_ops: usize::MAX,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -26,7 +26,9 @@ use crate::error::{Error, RdsTransactionRetryFailedSnafu, Result, UnexpectedSnaf
|
||||
use crate::kv_backend::txn::{
|
||||
Compare, Txn as KvTxn, TxnOp, TxnOpResponse, TxnResponse as KvTxnResponse,
|
||||
};
|
||||
use crate::kv_backend::{ClosableKvBackend, KvBackend, TxnService};
|
||||
use crate::kv_backend::{
|
||||
ClosableKvBackend, KvBackend, KvBackendCapabilities, TxnCapability, TxnService,
|
||||
};
|
||||
use crate::metrics::METRIC_META_TXN_REQUEST;
|
||||
use crate::rpc::KeyValue;
|
||||
use crate::rpc::store::{
|
||||
@@ -221,6 +223,8 @@ pub trait KvQueryExecutor<T: Executor> {
|
||||
Ok(PutResponse::default())
|
||||
}
|
||||
|
||||
/// Applies all writes atomically. Implementations that split a request across
|
||||
/// statements must run them in one transaction, reusing the caller's transaction if present.
|
||||
async fn batch_put_with_query_executor(
|
||||
&self,
|
||||
query_executor: &mut ExecutorImpl<'_, T>,
|
||||
@@ -506,6 +510,12 @@ where
|
||||
T: Executor + 'static,
|
||||
S: ExecutorFactory<T> + 'static,
|
||||
{
|
||||
fn capabilities(&self) -> KvBackendCapabilities {
|
||||
KvBackendCapabilities {
|
||||
atomic_batch_put: true,
|
||||
}
|
||||
}
|
||||
|
||||
fn name(&self) -> &str {
|
||||
T::name()
|
||||
}
|
||||
@@ -597,8 +607,10 @@ where
|
||||
RdsTransactionRetryFailedSnafu {}.fail()
|
||||
}
|
||||
|
||||
fn max_txn_ops(&self) -> usize {
|
||||
self.max_txn_ops
|
||||
fn txn_capability(&self) -> Option<TxnCapability> {
|
||||
Some(TxnCapability {
|
||||
max_ops: self.max_txn_ops,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -217,6 +217,16 @@ pub struct MySqlTemplateSet {
|
||||
delete_template: RangeTemplate,
|
||||
}
|
||||
|
||||
fn encoded_blob_len(len: usize) -> usize {
|
||||
let prefix = match len {
|
||||
0..=250 => 1,
|
||||
251..=65_535 => 3,
|
||||
65_536..=16_777_215 => 4,
|
||||
_ => 9,
|
||||
};
|
||||
len + prefix
|
||||
}
|
||||
|
||||
impl MySqlTemplateSet {
|
||||
/// Generates the sql for batch get.
|
||||
fn generate_batch_get_query(&self, key_len: usize) -> String {
|
||||
@@ -352,6 +362,26 @@ impl Transaction<'_> for MySqlTxnClient {
|
||||
|
||||
pub struct MySqlExecutorFactory {
|
||||
pool: Arc<Pool<MySql>>,
|
||||
max_allowed_packet: Option<usize>,
|
||||
}
|
||||
|
||||
impl MySqlExecutorFactory {
|
||||
async fn new(pool: MySqlPool) -> Self {
|
||||
const SQL: &str = "SELECT CAST(@@SESSION.max_allowed_packet AS UNSIGNED)";
|
||||
let max_allowed_packet = match sqlx::query_scalar::<_, u64>(SQL).fetch_one(&pool).await {
|
||||
Ok(bytes) => Some(bytes as usize),
|
||||
Err(err) => {
|
||||
warn!(
|
||||
"Failed to read MySQL max_allowed_packet, writing one key/value pair per statement: {err}"
|
||||
);
|
||||
None
|
||||
}
|
||||
};
|
||||
Self {
|
||||
pool: Arc::new(pool),
|
||||
max_allowed_packet,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
@@ -420,15 +450,17 @@ impl KvQueryExecutor<MySqlClient> for MySqlStore {
|
||||
if kvs.is_empty() {
|
||||
return Ok(BatchPutResponse::default());
|
||||
}
|
||||
if (req.prev_kv || kvs.len() > (*RDS_BATCH_SIZE).min(MAX_BATCH_PUT_KVS))
|
||||
let chunks = self.put_chunk_ranges(kvs)?;
|
||||
if (req.prev_kv || chunks.len() > 1)
|
||||
&& let ExecutorImpl::Default(executor) = query_executor
|
||||
{
|
||||
let mut txn = ExecutorImpl::Txn(executor.txn_executor().await?);
|
||||
let response = self.put_chunks(&mut txn, kvs, req.prev_kv).await?;
|
||||
let response = self.put_chunks(&mut txn, kvs, chunks, req.prev_kv).await?;
|
||||
txn.commit().await?;
|
||||
return Ok(response);
|
||||
}
|
||||
self.put_chunks(query_executor, kvs, req.prev_kv).await
|
||||
self.put_chunks(query_executor, kvs, chunks, req.prev_kv)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn batch_get_with_query_executor(
|
||||
@@ -537,16 +569,55 @@ impl MySqlStore {
|
||||
Ok(BatchGetResponse { kvs })
|
||||
}
|
||||
|
||||
/// Plans both PREPARE and EXECUTE packets before any write. A byte split
|
||||
/// requires the same transaction as a split at the bind-parameter limit.
|
||||
fn put_chunk_ranges(&self, kvs: &[KeyValue]) -> Result<Vec<std::ops::Range<usize>>> {
|
||||
let Some(limit) = self.executor_factory.max_allowed_packet else {
|
||||
return Ok((0..kvs.len()).map(|idx| idx..idx + 1).collect());
|
||||
};
|
||||
// Reserve 128 bytes for the fixed INSERT text and PREPARE command,
|
||||
// plus the table name and eight bytes per "(?, ?), " placeholder.
|
||||
let prepare_base = 128 + self.sql_template_set.table_name.len();
|
||||
let row_limit = (*RDS_BATCH_SIZE)
|
||||
.min(MAX_BATCH_PUT_KVS)
|
||||
.min(limit.saturating_sub(prepare_base) / 8);
|
||||
let mut chunks = Vec::new();
|
||||
let mut start = 0;
|
||||
let mut param_bytes = 0;
|
||||
for (idx, kv) in kvs.iter().enumerate() {
|
||||
// Two type descriptors and two length-encoded byte strings.
|
||||
let row_bytes = 4 + encoded_blob_len(kv.key.len()) + encoded_blob_len(kv.value.len());
|
||||
let rows = idx - start + 1;
|
||||
// Command/statement/flags/iteration count, new-params flag, NULL bitmap.
|
||||
let execute_bytes = 11 + (2 * rows).div_ceil(8) + param_bytes + row_bytes;
|
||||
if row_limit == 0 || 12 + row_bytes >= limit {
|
||||
return UnexpectedSnafu { err_msg: format!(
|
||||
"MySQL batch_put key/value pair cannot fit max_allowed_packet of {limit} bytes (key {}, value {})",
|
||||
kv.key.len(), kv.value.len()
|
||||
) }.fail();
|
||||
}
|
||||
if rows > row_limit || execute_bytes >= limit {
|
||||
chunks.push(start..idx);
|
||||
start = idx;
|
||||
param_bytes = 0;
|
||||
}
|
||||
param_bytes += row_bytes;
|
||||
}
|
||||
chunks.push(start..kvs.len());
|
||||
Ok(chunks)
|
||||
}
|
||||
|
||||
async fn put_chunks(
|
||||
&self,
|
||||
executor: &mut ExecutorImpl<'_, MySqlClient>,
|
||||
kvs: &[KeyValue],
|
||||
chunks: Vec<std::ops::Range<usize>>,
|
||||
prev_kv: bool,
|
||||
) -> Result<BatchPutResponse> {
|
||||
let mut prev_kvs = Vec::new();
|
||||
let chunk_size = (*RDS_BATCH_SIZE).min(MAX_BATCH_PUT_KVS);
|
||||
let mut params = Vec::with_capacity(kvs.len().min(chunk_size) * 2);
|
||||
for chunk in kvs.chunks(chunk_size) {
|
||||
let mut params = Vec::new();
|
||||
for range in chunks {
|
||||
let chunk = &kvs[range];
|
||||
let (select, update) = self
|
||||
.sql_template_set
|
||||
.generate_batch_upsert_query(chunk.len());
|
||||
@@ -707,9 +778,7 @@ impl MySqlStore {
|
||||
max_txn_ops,
|
||||
sql_template_set,
|
||||
txn_retry_count: RDS_STORE_TXN_RETRY_COUNT,
|
||||
executor_factory: MySqlExecutorFactory {
|
||||
pool: Arc::new(pool),
|
||||
},
|
||||
executor_factory: MySqlExecutorFactory::new(pool).await,
|
||||
_phantom: PhantomData,
|
||||
}))
|
||||
}
|
||||
@@ -736,6 +805,15 @@ mod tests {
|
||||
use crate::rpc::store::{PutRequest, RangeRequest};
|
||||
use crate::test_util::test_certs_dir;
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_packet_limit_query_failure_leaves_limit_unknown() {
|
||||
let pool =
|
||||
sqlx::mysql::MySqlPoolOptions::new().connect_lazy_with(MySqlConnectOptions::new());
|
||||
pool.close().await;
|
||||
let factory = MySqlExecutorFactory::new(pool).await;
|
||||
assert_eq!(factory.max_allowed_packet, None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_close_backend() {
|
||||
let pool =
|
||||
@@ -745,6 +823,7 @@ mod tests {
|
||||
txn_retry_count: RDS_STORE_TXN_RETRY_COUNT,
|
||||
executor_factory: MySqlExecutorFactory {
|
||||
pool: Arc::new(pool.clone()),
|
||||
max_allowed_packet: None,
|
||||
},
|
||||
sql_template_set: MySqlTemplateFactory::new("close_test").build(),
|
||||
_phantom: PhantomData,
|
||||
@@ -846,9 +925,7 @@ mod tests {
|
||||
max_txn_ops: 128,
|
||||
sql_template_set: sql_templates,
|
||||
txn_retry_count: RDS_STORE_TXN_RETRY_COUNT,
|
||||
executor_factory: MySqlExecutorFactory {
|
||||
pool: Arc::new(pool),
|
||||
},
|
||||
executor_factory: MySqlExecutorFactory::new(pool).await,
|
||||
_phantom: PhantomData,
|
||||
})
|
||||
}
|
||||
@@ -1254,7 +1331,74 @@ mod tests {
|
||||
"successful earlier chunks must roll back"
|
||||
);
|
||||
}
|
||||
drop_table(&store.executor_factory.pool, &table).await;
|
||||
// Two 700-byte values fit the bind limit but exceed this packet budget.
|
||||
// The trigger rejects the last chunk after the first one succeeds.
|
||||
let mut store = store;
|
||||
let packet_limit = store.executor_factory.max_allowed_packet;
|
||||
store.executor_factory.max_allowed_packet = Some(1024);
|
||||
let make_kv = |key: u8, value| KeyValue {
|
||||
key: vec![key],
|
||||
value,
|
||||
};
|
||||
let kvs = vec![
|
||||
make_kv(1, vec![1; 700]),
|
||||
make_kv(2, vec![2; 700]),
|
||||
make_kv(3, b"fail".to_vec()),
|
||||
];
|
||||
assert!(store.put_chunk_ranges(&kvs).unwrap().len() >= 2);
|
||||
assert!(
|
||||
store
|
||||
.batch_put(BatchPutRequest {
|
||||
kvs,
|
||||
prev_kv: false
|
||||
})
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
let reader = build_mysql_kv_backend(&table).await.unwrap();
|
||||
assert!(
|
||||
reader
|
||||
.range(RangeRequest::new().with_range(vec![0], vec![0]))
|
||||
.await
|
||||
.unwrap()
|
||||
.kvs
|
||||
.is_empty()
|
||||
);
|
||||
let err = store
|
||||
.put_chunk_ranges(&[make_kv(1, vec![0; 1024])])
|
||||
.unwrap_err();
|
||||
assert!(err.to_string().contains("max_allowed_packet"));
|
||||
store.executor_factory.max_allowed_packet = None;
|
||||
let large = make_kv(4, vec![4; 5 * 1024 * 1024]);
|
||||
let kvs = vec![large.clone(), make_kv(5, b"fail".to_vec())];
|
||||
assert_eq!(store.put_chunk_ranges(&kvs).unwrap(), [0..1, 1..2]);
|
||||
// When the server accepts this value, losing the limit probe must not reject it.
|
||||
if packet_limit.is_some_and(|limit| limit > large.value.len() + 1024) {
|
||||
store
|
||||
.batch_put(BatchPutRequest {
|
||||
kvs: vec![large.clone()],
|
||||
prev_kv: false,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(reader.get(&large.key).await.unwrap().unwrap(), large);
|
||||
}
|
||||
let kvs = vec![make_kv(6, b"ok".to_vec()), make_kv(7, b"fail".to_vec())];
|
||||
assert!(
|
||||
store
|
||||
.batch_put(BatchPutRequest {
|
||||
kvs,
|
||||
prev_kv: false
|
||||
})
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(reader.get(&[6]).await.unwrap().is_none());
|
||||
store.executor_factory.max_allowed_packet = packet_limit;
|
||||
let pool = store.executor_factory.pool.clone();
|
||||
crate::kv_backend::test::check_segmented_checkpoint(Arc::new(store), Arc::new(reader))
|
||||
.await;
|
||||
drop_table(&pool, &table).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -84,6 +84,8 @@ impl Default for TlsOption {
|
||||
}
|
||||
}
|
||||
|
||||
// Target Bind payload per upsert. A single larger KV still gets its own statement.
|
||||
const BATCH_PUT_TARGET_BYTES: usize = 4 * 1024 * 1024;
|
||||
const PG_STORE_NAME: &str = "pg_store";
|
||||
|
||||
pub struct PgClient(deadpool::managed::Object<deadpool_postgres::Manager>);
|
||||
@@ -725,15 +727,18 @@ impl KvQueryExecutor<PgClient> for PgStore {
|
||||
req: BatchPutRequest,
|
||||
) -> Result<BatchPutResponse> {
|
||||
let chunk_size = (*RDS_BATCH_SIZE).min(u16::MAX as usize / 3);
|
||||
if req.kvs.len() > chunk_size
|
||||
let chunks = batch_put_chunks(&req.kvs, chunk_size);
|
||||
if chunks.len() > 1
|
||||
&& let ExecutorImpl::Default(client) = query_executor
|
||||
{
|
||||
let mut transaction = ExecutorImpl::Txn(client.txn_executor().await?);
|
||||
let response = self.put_chunks(&mut transaction, &req, chunk_size).await?;
|
||||
let response = self
|
||||
.put_chunks(&mut transaction, chunks, req.prev_kv)
|
||||
.await?;
|
||||
transaction.commit().await?;
|
||||
return Ok(response);
|
||||
}
|
||||
self.put_chunks(query_executor, &req, chunk_size).await
|
||||
self.put_chunks(query_executor, chunks, req.prev_kv).await
|
||||
}
|
||||
|
||||
/// Batch get with certain client. It's needed for a client with transaction.
|
||||
@@ -913,6 +918,26 @@ impl PgStore {
|
||||
}
|
||||
}
|
||||
|
||||
fn batch_put_chunks(kvs: &[KeyValue], max_rows: usize) -> Vec<&[KeyValue]> {
|
||||
let mut chunks = Vec::new();
|
||||
let mut start = 0;
|
||||
let mut bytes = 0;
|
||||
for (idx, kv) in kvs.iter().enumerate() {
|
||||
// Bind sends the key twice and the value once, each with a four-byte length.
|
||||
let row_bytes = kv.key.len() * 2 + kv.value.len() + 12;
|
||||
if idx > start && (idx - start == max_rows || bytes + row_bytes > BATCH_PUT_TARGET_BYTES) {
|
||||
chunks.push(&kvs[start..idx]);
|
||||
start = idx;
|
||||
bytes = 0;
|
||||
}
|
||||
bytes += row_bytes;
|
||||
}
|
||||
if start < kvs.len() {
|
||||
chunks.push(&kvs[start..]);
|
||||
}
|
||||
chunks
|
||||
}
|
||||
|
||||
impl PgStore {
|
||||
async fn get_chunks(
|
||||
&self,
|
||||
@@ -944,11 +969,11 @@ impl PgStore {
|
||||
async fn put_chunks(
|
||||
&self,
|
||||
executor: &mut ExecutorImpl<'_, PgClient>,
|
||||
req: &BatchPutRequest,
|
||||
chunk_size: usize,
|
||||
chunks: Vec<&[KeyValue]>,
|
||||
prev_kv: bool,
|
||||
) -> Result<BatchPutResponse> {
|
||||
let mut prev_kvs = Vec::new();
|
||||
for chunk in req.kvs.chunks(chunk_size) {
|
||||
for chunk in chunks {
|
||||
let mut params = Vec::with_capacity(chunk.len() * 3);
|
||||
params.extend(chunk.iter().map(|kv| &kv.key));
|
||||
for kv in chunk {
|
||||
@@ -964,7 +989,7 @@ impl PgStore {
|
||||
RDS_STORE_OP_BATCH_PUT,
|
||||
""
|
||||
)?;
|
||||
if req.prev_kv {
|
||||
if prev_kv {
|
||||
prev_kvs.extend(kvs);
|
||||
}
|
||||
}
|
||||
@@ -1527,6 +1552,75 @@ mod tests {
|
||||
unprepare_kv(&backend, prefix).await;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_batch_put_chunk_byte_budget() {
|
||||
let kv = KeyValue {
|
||||
key: vec![0; 2],
|
||||
value: vec![1; BATCH_PUT_TARGET_BYTES / 2 - 16],
|
||||
};
|
||||
let mut kvs = vec![kv.clone(), kv];
|
||||
assert_eq!(batch_put_chunks(&kvs, 128).len(), 1);
|
||||
kvs[1].value.push(1);
|
||||
assert_eq!(batch_put_chunks(&kvs, 128), [&kvs[..1], &kvs[1..]]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_pg_segmented_checkpoint() {
|
||||
maybe_skip_postgres_integration_test!();
|
||||
let table = format!("checkpoint_{}", uuid::Uuid::new_v4().simple());
|
||||
let backend = build_pg_kv_backend(&table).await.unwrap();
|
||||
let reader = build_pg_kv_backend(&table).await.unwrap();
|
||||
let client = backend.executor_factory.pool.get().await.unwrap();
|
||||
client
|
||||
.batch_execute(&format!(
|
||||
"ALTER TABLE {table} ADD CHECK (v <> convert_to('fail', 'UTF8'))"
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
let large = KeyValue {
|
||||
key: b"large-singleton".to_vec(),
|
||||
value: vec![1; BATCH_PUT_TARGET_BYTES + 1],
|
||||
};
|
||||
let kvs = vec![
|
||||
large.clone(),
|
||||
KeyValue {
|
||||
key: b"rejected".to_vec(),
|
||||
value: b"fail".to_vec(),
|
||||
},
|
||||
];
|
||||
assert_eq!(
|
||||
batch_put_chunks(&kvs, 128)
|
||||
.iter()
|
||||
.map(|chunk| chunk.len())
|
||||
.collect::<Vec<_>>(),
|
||||
[1, 1]
|
||||
);
|
||||
assert!(
|
||||
backend
|
||||
.batch_put(BatchPutRequest {
|
||||
kvs,
|
||||
prev_kv: false
|
||||
})
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(reader.get(&large.key).await.unwrap().is_none());
|
||||
backend
|
||||
.batch_put(BatchPutRequest {
|
||||
kvs: vec![large.clone()],
|
||||
prev_kv: false,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(reader.get(&large.key).await.unwrap().unwrap(), large);
|
||||
crate::kv_backend::test::check_segmented_checkpoint(Arc::new(backend), Arc::new(reader))
|
||||
.await;
|
||||
client
|
||||
.batch_execute(&format!("DROP TABLE {table}"))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_pg_later_write_chunk_failure_rolls_back() {
|
||||
maybe_skip_postgres_integration_test!();
|
||||
|
||||
@@ -16,7 +16,7 @@ use std::any::Any;
|
||||
|
||||
use crate::error::{ReadOnlyKvBackendSnafu, Result};
|
||||
use crate::kv_backend::txn::{Txn, TxnOp, TxnResponse};
|
||||
use crate::kv_backend::{KvBackend, KvBackendRef, TxnService};
|
||||
use crate::kv_backend::{KvBackend, KvBackendRef, TxnCapability, TxnService};
|
||||
use crate::rpc::KeyValue;
|
||||
use crate::rpc::store::{
|
||||
BatchDeleteRequest, BatchDeleteResponse, BatchGetRequest, BatchGetResponse, BatchPutRequest,
|
||||
@@ -69,8 +69,8 @@ impl TxnService for ReadOnlyKvBackend {
|
||||
self.inner.txn(txn).await
|
||||
}
|
||||
|
||||
fn max_txn_ops(&self) -> usize {
|
||||
self.inner.max_txn_ops()
|
||||
fn txn_capability(&self) -> Option<TxnCapability> {
|
||||
self.inner.txn_capability()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -175,8 +175,8 @@ mod tests {
|
||||
})
|
||||
}
|
||||
|
||||
fn max_txn_ops(&self) -> usize {
|
||||
7
|
||||
fn txn_capability(&self) -> Option<TxnCapability> {
|
||||
Some(TxnCapability { max_ops: 7 })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -276,7 +276,12 @@ mod tests {
|
||||
async fn test_read_only_backend_rejects_write_txn() {
|
||||
let backend = read_only_backend().await;
|
||||
|
||||
assert_eq!(backend.max_txn_ops(), usize::MAX);
|
||||
assert_eq!(
|
||||
backend.txn_capability(),
|
||||
Some(TxnCapability {
|
||||
max_ops: usize::MAX
|
||||
})
|
||||
);
|
||||
assert_read_only(
|
||||
backend
|
||||
.txn(Txn::put_if_not_exists(b"k3".to_vec(), b"v3".to_vec()))
|
||||
@@ -288,7 +293,7 @@ mod tests {
|
||||
async fn test_read_only_backend_delegates_read_txn() {
|
||||
let backend = ReadOnlyKvBackend::new(Arc::new(TxnOnlyBackend));
|
||||
|
||||
assert_eq!(backend.max_txn_ops(), 7);
|
||||
assert_eq!(backend.txn_capability(), Some(TxnCapability { max_ops: 7 }));
|
||||
let resp = backend
|
||||
.txn(Txn::new().and_then(vec![TxnOp::Get(b"k1".to_vec())]))
|
||||
.await
|
||||
|
||||
@@ -23,6 +23,71 @@ use crate::rpc::KeyValue;
|
||||
use crate::rpc::store::{BatchGetRequest, PutRequest};
|
||||
use crate::util;
|
||||
|
||||
#[cfg(any(test, feature = "testing"))]
|
||||
pub async fn check_atomic_checkpoint_round_trip(backend: KvBackendRef) {
|
||||
use common_procedure::store::state_store::StateStore;
|
||||
use futures::TryStreamExt;
|
||||
|
||||
use crate::state_store::KvStateStore;
|
||||
|
||||
assert!(backend.capabilities().atomic_batch_put);
|
||||
let store = KvStateStore::new(backend).with_max_value_size(Some(2));
|
||||
store.put("step", b"abcde".to_vec()).await.unwrap();
|
||||
let mut stream = store.walk_top_down("step").await.unwrap();
|
||||
let (keys, value) = stream.try_next().await.unwrap().unwrap();
|
||||
assert_eq!(keys.keys(), ["step", "step/0000000001", "step/0000000002"]);
|
||||
assert_eq!(value, b"abcde");
|
||||
assert!(stream.try_next().await.unwrap().is_none());
|
||||
}
|
||||
|
||||
/// Exercises the procedure path against a table configured to reject the value "fail".
|
||||
#[cfg(all(test, any(feature = "pg_kvbackend", feature = "mysql_kvbackend")))]
|
||||
pub(crate) async fn check_segmented_checkpoint(writer: KvBackendRef, reader: KvBackendRef) {
|
||||
use common_procedure::store::state_store::StateStore;
|
||||
use futures::TryStreamExt;
|
||||
|
||||
use crate::state_store::KvStateStore;
|
||||
|
||||
let store = KvStateStore::new(writer.clone()).with_max_value_size(Some(4));
|
||||
assert!(store.put("step", b"11112222fail".to_vec()).await.is_err());
|
||||
let req = RangeRequest::new().with_prefix(b"/__procedure__/step".to_vec());
|
||||
assert!(reader.range(req.clone()).await.unwrap().kvs.is_empty());
|
||||
|
||||
store.put("step", b"aaaabbbbcccc".to_vec()).await.unwrap();
|
||||
let original = reader.range(req.clone()).await.unwrap().kvs;
|
||||
assert_eq!(original.len(), 3);
|
||||
assert!(store.put("step", b"11112222fail".to_vec()).await.is_err());
|
||||
assert_eq!(reader.range(req).await.unwrap().kvs, original);
|
||||
store.put("step", b"111122223333".to_vec()).await.unwrap();
|
||||
|
||||
let read_store = KvStateStore::new(reader);
|
||||
let checkpoints: Vec<_> = read_store
|
||||
.walk_top_down("step")
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(checkpoints.len(), 1);
|
||||
assert_eq!(checkpoints[0].1, b"111122223333");
|
||||
|
||||
let large = vec![42; 2 * 1024 * 1024 + 1];
|
||||
KvStateStore::new(writer)
|
||||
.with_max_value_size(Some(1024 * 1024))
|
||||
.put("large", large.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
let checkpoints: Vec<_> = read_store
|
||||
.walk_top_down("large")
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(checkpoints.len(), 1);
|
||||
assert_eq!(checkpoints[0].1, large);
|
||||
}
|
||||
|
||||
pub fn mock_kvs(prefix: Vec<u8>) -> Vec<KeyValue> {
|
||||
vec![
|
||||
KeyValue {
|
||||
|
||||
@@ -22,8 +22,8 @@ use crate::error::Result;
|
||||
use crate::kv_backend::txn::{Txn, TxnResponse};
|
||||
use crate::kv_backend::{
|
||||
BatchDeleteRequest, BatchDeleteResponse, BatchGetRequest, BatchGetResponse, BatchPutRequest,
|
||||
BatchPutResponse, DeleteRangeRequest, DeleteRangeResponse, KvBackend, KvBackendRef, PutRequest,
|
||||
PutResponse, RangeRequest, RangeResponse, TxnService,
|
||||
BatchPutResponse, DeleteRangeRequest, DeleteRangeResponse, KvBackend, KvBackendCapabilities,
|
||||
KvBackendRef, PutRequest, PutResponse, RangeRequest, RangeResponse, TxnCapability, TxnService,
|
||||
};
|
||||
|
||||
pub type MockFn<Req, Resp> = Arc<dyn Fn(Req) -> Result<Resp> + Send + Sync>;
|
||||
@@ -35,6 +35,8 @@ pub type AsyncMockFn<Req, Resp> =
|
||||
/// A mock kv backend for testing.
|
||||
#[derive(Builder)]
|
||||
pub struct MockKvBackend {
|
||||
#[builder(default)]
|
||||
pub capabilities: KvBackendCapabilities,
|
||||
#[builder(setter(strip_option), default)]
|
||||
pub range_fn: Option<MockFn<RangeRequest, RangeResponse>>,
|
||||
/// Takes precedence over the synchronous range callback when set.
|
||||
@@ -68,13 +70,19 @@ impl TxnService for MockKvBackend {
|
||||
}
|
||||
}
|
||||
|
||||
fn max_txn_ops(&self) -> usize {
|
||||
self.max_txn_ops.unwrap()
|
||||
fn txn_capability(&self) -> Option<TxnCapability> {
|
||||
self.max_txn_ops
|
||||
.or_else(|| self.txn.as_ref().map(|_| usize::MAX))
|
||||
.map(|max_ops| TxnCapability { max_ops })
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl KvBackend for MockKvBackend {
|
||||
fn capabilities(&self) -> KvBackendCapabilities {
|
||||
self.capabilities
|
||||
}
|
||||
|
||||
fn name(&self) -> &str {
|
||||
"mock_kv_backend"
|
||||
}
|
||||
@@ -151,13 +159,17 @@ impl TxnService for TxnObservingKvBackend {
|
||||
self.inner.txn(txn).await
|
||||
}
|
||||
|
||||
fn max_txn_ops(&self) -> usize {
|
||||
self.inner.max_txn_ops()
|
||||
fn txn_capability(&self) -> Option<TxnCapability> {
|
||||
self.inner.txn_capability()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl KvBackend for TxnObservingKvBackend {
|
||||
fn capabilities(&self) -> KvBackendCapabilities {
|
||||
self.inner.capabilities()
|
||||
}
|
||||
|
||||
fn name(&self) -> &str {
|
||||
self.inner.name()
|
||||
}
|
||||
|
||||
@@ -20,6 +20,13 @@ use crate::rpc::store::{DeleteRangeResponse, PutResponse, RangeResponse};
|
||||
|
||||
mod etcd;
|
||||
|
||||
/// Limits for backends that support explicit transactions.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct TxnCapability {
|
||||
/// Maximum number of operations permitted in one transaction.
|
||||
pub max_ops: usize,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
pub trait TxnService: Sync + Send {
|
||||
type Error: ErrorExt;
|
||||
@@ -28,9 +35,9 @@ pub trait TxnService: Sync + Send {
|
||||
unimplemented!("txn is not implemented")
|
||||
}
|
||||
|
||||
/// Maximum number of operations permitted in a transaction.
|
||||
fn max_txn_ops(&self) -> usize {
|
||||
unimplemented!("txn is not implemented")
|
||||
/// Returns None when explicit transactions are unsupported.
|
||||
fn txn_capability(&self) -> Option<TxnCapability> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -92,6 +92,9 @@ impl State for ResolveColumnMetadata {
|
||||
ctx.persistent_ctx.table_info_value = Some(table_info_value);
|
||||
|
||||
if let Some(column_metadatas) = check_column_metadatas_consistent(&self.region_metadata) {
|
||||
// The consistent regions share their key: order the tags as the regions keep them, which
|
||||
// also checks that the region's primary key matches its tag columns. Column order still
|
||||
// comes from the stored `TableInfo`; see `build_table_meta_from_column_metadatas`.
|
||||
let column_metadatas =
|
||||
reorder_tag_columns(&column_metadatas, &self.region_metadata[0].primary_key)?;
|
||||
// Safety: fetched in the above.
|
||||
|
||||
@@ -358,15 +358,24 @@ pub(crate) fn check_column_metadata_invariants(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Builds a [`TableMeta`] from the provided [`ColumnMetadata`]s.
|
||||
/// Builds a [`TableMeta`] from the provided [`ColumnMetadata`]s, preserving schema column order
|
||||
/// from `table_meta` and taking the primary key order from the input tags.
|
||||
///
|
||||
/// The input [`ColumnMetadata`]s determine which columns currently exist in region metadata:
|
||||
/// - Columns present in `table_meta` but missing from `column_metadata` are dropped.
|
||||
/// - Columns present in both retain the column order from `table_meta.schema`.
|
||||
/// - Columns present only in `column_metadata` are appended.
|
||||
/// - Primary key order follows the tag columns in `column_metadata`, which the physical-table
|
||||
/// reconcile paths feed in the regions' key order (`table_meta.primary_key_indices` only
|
||||
/// determines which columns must remain tags). The logical-table reconcile path feeds columns
|
||||
/// in column-position order and relies on a subsequent `sort_columns()` call.
|
||||
///
|
||||
/// Returns an error if:
|
||||
/// - Any column is missing in the `name_to_ids`(if `name_to_ids` is provided).
|
||||
/// - The column id in table metadata is not the same as the column id in the column metadata.(if `name_to_ids` is provided)
|
||||
/// - The table index is missing in the column metadata.
|
||||
/// - Any primary key column of `table_meta` is not [`SemanticType::Tag`] in `column_metadata`.
|
||||
/// - The primary key or partition key columns are missing in the column metadata.
|
||||
///
|
||||
/// TODO(weny): add tests
|
||||
pub(crate) fn build_table_meta_from_column_metadatas(
|
||||
table_id: TableId,
|
||||
table_ref: TableReference,
|
||||
@@ -434,11 +443,30 @@ pub(crate) fn build_table_meta_from_column_metadatas(
|
||||
);
|
||||
}
|
||||
|
||||
let mut ordered_column_metadatas = Vec::with_capacity(column_metadata.len());
|
||||
let mut existing_names = HashSet::with_capacity(column_schemas.len());
|
||||
|
||||
// Preserves the original table column order from `table_meta.schema`.
|
||||
for col_schema in column_schemas {
|
||||
if let Some(col) = column_in_column_metadata.get(col_schema.name.as_str()) {
|
||||
ordered_column_metadatas.push(*col);
|
||||
existing_names.insert(col_schema.name.as_str());
|
||||
}
|
||||
}
|
||||
|
||||
// Appends any newly added columns from `column_metadata`.
|
||||
for col in column_metadata {
|
||||
if !existing_names.contains(col.column_schema.name.as_str()) {
|
||||
ordered_column_metadatas.push(col);
|
||||
}
|
||||
}
|
||||
|
||||
let mut new_raw_table_meta = table_meta.clone();
|
||||
let primary_key_indices = &mut new_raw_table_meta.primary_key_indices;
|
||||
let partition_key_indices = &mut new_raw_table_meta.partition_key_indices;
|
||||
let value_indices = &mut new_raw_table_meta.value_indices;
|
||||
let mut columns = Vec::with_capacity(column_metadata.len());
|
||||
let mut columns = Vec::with_capacity(ordered_column_metadatas.len());
|
||||
let mut column_name_to_index = HashMap::with_capacity(ordered_column_metadatas.len());
|
||||
let column_ids = &mut new_raw_table_meta.column_ids;
|
||||
let next_column_id = &mut new_raw_table_meta.next_column_id;
|
||||
|
||||
@@ -447,24 +475,47 @@ pub(crate) fn build_table_meta_from_column_metadatas(
|
||||
primary_key_indices.clear();
|
||||
partition_key_indices.clear();
|
||||
|
||||
for (idx, col) in column_metadata.iter().enumerate() {
|
||||
if partition_key_names.contains(&col.column_schema.name.as_str()) {
|
||||
partition_key_indices.push(idx);
|
||||
}
|
||||
match col.semantic_type {
|
||||
SemanticType::Tag => {
|
||||
primary_key_indices.push(idx);
|
||||
}
|
||||
SemanticType::Field => {
|
||||
value_indices.push(idx);
|
||||
}
|
||||
SemanticType::Timestamp => {
|
||||
value_indices.push(idx);
|
||||
}
|
||||
for (idx, col) in ordered_column_metadatas.iter().enumerate() {
|
||||
if col.semantic_type != SemanticType::Tag {
|
||||
value_indices.push(idx);
|
||||
}
|
||||
|
||||
columns.push(col.column_schema.clone());
|
||||
column_ids.push(col.column_id);
|
||||
column_name_to_index.insert(col.column_schema.name.as_str(), idx);
|
||||
}
|
||||
|
||||
// Physical-table reconciliation supplies tags in region primary key order.
|
||||
for col in column_metadata
|
||||
.iter()
|
||||
.filter(|c| c.semantic_type == SemanticType::Tag)
|
||||
{
|
||||
primary_key_indices.push(column_name_to_index[col.column_schema.name.as_str()]);
|
||||
}
|
||||
|
||||
// Ensures every stored primary key column is still a tag in the region metadata.
|
||||
for old_idx in &table_meta.primary_key_indices {
|
||||
let col_schema = &column_schemas[*old_idx];
|
||||
if let Some(col) = column_in_column_metadata.get(col_schema.name.as_str()) {
|
||||
ensure!(
|
||||
col.semantic_type == SemanticType::Tag,
|
||||
UnexpectedSnafu {
|
||||
err_msg: format!(
|
||||
"Primary key column '{}' has invalid semantic type '{:?}', expected Tag, table: {}, table_id: {}",
|
||||
col_schema.name, col.semantic_type, table_ref, table_id
|
||||
),
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Preserves the order of partition keys as defined in the original table info.
|
||||
for old_idx in &table_meta.partition_key_indices {
|
||||
let col_schema = &column_schemas[*old_idx];
|
||||
let Some(&new_idx) = column_name_to_index.get(col_schema.name.as_str()) else {
|
||||
continue;
|
||||
};
|
||||
partition_key_indices.push(new_idx);
|
||||
}
|
||||
|
||||
*next_column_id = column_ids
|
||||
@@ -1265,6 +1316,180 @@ mod tests {
|
||||
assert_matches!(err, Error::MissingColumnInColumnMetadata { .. });
|
||||
}
|
||||
|
||||
fn new_test_q8_raw_table_info() -> (TableMeta, HashMap<String, u32>) {
|
||||
let column_schemas = vec![
|
||||
ColumnSchema::new(
|
||||
"ts",
|
||||
ConcreteDataType::timestamp_millisecond_datatype(),
|
||||
false,
|
||||
)
|
||||
.with_time_index(true),
|
||||
ColumnSchema::new("a", ConcreteDataType::string_datatype(), true),
|
||||
ColumnSchema::new("b", ConcreteDataType::string_datatype(), true),
|
||||
];
|
||||
let schema = SchemaBuilder::try_from(column_schemas)
|
||||
.unwrap()
|
||||
.version(1)
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
let mut table_meta_builder = TableMetaBuilder::empty();
|
||||
let mut table_meta = table_meta_builder
|
||||
.schema(Arc::new(schema))
|
||||
.primary_key_indices(vec![2, 1])
|
||||
.next_column_id(4)
|
||||
.build()
|
||||
.unwrap();
|
||||
table_meta.column_ids = vec![1, 2, 3];
|
||||
|
||||
let name_to_ids = HashMap::from([
|
||||
("ts".to_string(), 1),
|
||||
("a".to_string(), 2),
|
||||
("b".to_string(), 3),
|
||||
]);
|
||||
|
||||
(table_meta, name_to_ids)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_build_table_meta_preserves_column_order_and_primary_key_indices() {
|
||||
let (mut table_meta, name_to_ids) = new_test_q8_raw_table_info();
|
||||
table_meta.partition_key_indices = vec![2, 1];
|
||||
let table_id = 100;
|
||||
let table_ref = TableReference::full("test_catalog", "test_schema", "test_table");
|
||||
|
||||
let region_column_metadatas = vec![
|
||||
ColumnMetadata {
|
||||
column_schema: ColumnSchema::new(
|
||||
"ts",
|
||||
ConcreteDataType::timestamp_millisecond_datatype(),
|
||||
false,
|
||||
)
|
||||
.with_time_index(true),
|
||||
semantic_type: SemanticType::Timestamp,
|
||||
column_id: 1,
|
||||
},
|
||||
ColumnMetadata {
|
||||
column_schema: ColumnSchema::new("a", ConcreteDataType::string_datatype(), true),
|
||||
semantic_type: SemanticType::Tag,
|
||||
column_id: 2,
|
||||
},
|
||||
ColumnMetadata {
|
||||
column_schema: ColumnSchema::new("b", ConcreteDataType::string_datatype(), true),
|
||||
semantic_type: SemanticType::Tag,
|
||||
column_id: 3,
|
||||
},
|
||||
];
|
||||
|
||||
// 1. Consistent case where region columns match table schema order:
|
||||
// Column order comes from table_meta; the primary key order follows the input tags.
|
||||
let new_table_meta = build_table_meta_from_column_metadatas(
|
||||
table_id,
|
||||
table_ref,
|
||||
&table_meta,
|
||||
Some(name_to_ids.clone()),
|
||||
®ion_column_metadatas,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(new_table_meta.primary_key_indices, vec![1, 2]);
|
||||
assert_eq!(new_table_meta.partition_key_indices, vec![2, 1]);
|
||||
assert_eq!(new_table_meta.column_ids, table_meta.column_ids);
|
||||
|
||||
// 2. Case where input column metadata has reordered tags (e.g. ts, b, a):
|
||||
// Table schema column order must still be preserved according to table_meta.schema.
|
||||
let reordered_column_metadatas = vec![
|
||||
region_column_metadatas[0].clone(),
|
||||
region_column_metadatas[2].clone(),
|
||||
region_column_metadatas[1].clone(),
|
||||
];
|
||||
let new_table_meta = build_table_meta_from_column_metadatas(
|
||||
table_id,
|
||||
table_ref,
|
||||
&table_meta,
|
||||
Some(name_to_ids.clone()),
|
||||
&reordered_column_metadatas,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(new_table_meta, table_meta);
|
||||
|
||||
// 3. Case where a new field column is added:
|
||||
let mut extended_column_metadatas = region_column_metadatas.clone();
|
||||
extended_column_metadatas.push(ColumnMetadata {
|
||||
column_schema: ColumnSchema::new("c", ConcreteDataType::int32_datatype(), true),
|
||||
semantic_type: SemanticType::Field,
|
||||
column_id: 4,
|
||||
});
|
||||
let mut extended_name_to_ids = name_to_ids;
|
||||
extended_name_to_ids.insert("c".to_string(), 4);
|
||||
|
||||
let new_table_meta = build_table_meta_from_column_metadatas(
|
||||
table_id,
|
||||
table_ref,
|
||||
&table_meta,
|
||||
Some(extended_name_to_ids),
|
||||
&extended_column_metadatas,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
new_table_meta
|
||||
.schema
|
||||
.column_schemas()
|
||||
.iter()
|
||||
.map(|c| c.name.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
vec!["ts", "a", "b", "c"]
|
||||
);
|
||||
assert_eq!(new_table_meta.primary_key_indices, vec![1, 2]);
|
||||
assert_eq!(new_table_meta.value_indices, vec![0, 3]);
|
||||
assert_eq!(new_table_meta.column_ids, vec![1, 2, 3, 4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_build_table_meta_rejects_non_tag_primary_key() {
|
||||
let (table_meta, name_to_ids) = new_test_q8_raw_table_info();
|
||||
let table_id = 100;
|
||||
let table_ref = TableReference::full("test_catalog", "test_schema", "test_table");
|
||||
|
||||
// Input column metadata erroneously reports primary key column 'b' as Field instead of Tag
|
||||
let invalid_column_metadatas = vec![
|
||||
ColumnMetadata {
|
||||
column_schema: ColumnSchema::new(
|
||||
"ts",
|
||||
ConcreteDataType::timestamp_millisecond_datatype(),
|
||||
false,
|
||||
)
|
||||
.with_time_index(true),
|
||||
semantic_type: SemanticType::Timestamp,
|
||||
column_id: 1,
|
||||
},
|
||||
ColumnMetadata {
|
||||
column_schema: ColumnSchema::new("a", ConcreteDataType::string_datatype(), true),
|
||||
semantic_type: SemanticType::Tag,
|
||||
column_id: 2,
|
||||
},
|
||||
ColumnMetadata {
|
||||
column_schema: ColumnSchema::new("b", ConcreteDataType::string_datatype(), true),
|
||||
semantic_type: SemanticType::Field,
|
||||
column_id: 3,
|
||||
},
|
||||
];
|
||||
|
||||
let err = build_table_meta_from_column_metadatas(
|
||||
table_id,
|
||||
table_ref,
|
||||
&table_meta,
|
||||
Some(name_to_ids),
|
||||
&invalid_column_metadatas,
|
||||
)
|
||||
.unwrap_err();
|
||||
|
||||
assert_matches!(err, Error::Unexpected { .. });
|
||||
assert!(err.to_string().contains("expected Tag"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_reconciliation_columns_follow_primary_key_order() {
|
||||
let columns = vec![
|
||||
|
||||
@@ -34,7 +34,7 @@ use crate::kv_backend::KvBackendRef;
|
||||
use crate::kv_backend::txn::{Compare, CompareOp, Txn, TxnOp};
|
||||
use crate::range_stream::PaginationStream;
|
||||
use crate::rpc::KeyValue;
|
||||
use crate::rpc::store::{BatchDeleteRequest, PutRequest, RangeRequest};
|
||||
use crate::rpc::store::{BatchDeleteRequest, BatchPutRequest, PutRequest, RangeRequest};
|
||||
|
||||
const DELIMITER: &str = "/";
|
||||
|
||||
@@ -130,38 +130,35 @@ impl StateStore for KvStateStore {
|
||||
Ok(())
|
||||
}
|
||||
SplitValue::Multiple(values) => {
|
||||
// Note:
|
||||
// The length of values can be up to usize::MAX.
|
||||
// The KeySet::with_segment_suffix method uses a 10-digit number to store the segment number,
|
||||
// which is large enough for the usize type.
|
||||
let segments = values.into_iter().enumerate().map(|(idx, value)| {
|
||||
let segment_key = if idx == 0 {
|
||||
key.clone()
|
||||
} else {
|
||||
KeySet::with_segment_suffix(&key, idx)
|
||||
};
|
||||
KeyValue {
|
||||
key: segment_key.into_bytes(),
|
||||
value,
|
||||
}
|
||||
});
|
||||
|
||||
// The first segment key: "0b00001111"
|
||||
// The 2nd segment key: "0b00001111/0000000001"
|
||||
// The 3rd segment key: "0b00001111/0000000002"
|
||||
let operations = values
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(idx, value)| {
|
||||
let key = if idx > 0 {
|
||||
KeySet::with_segment_suffix(&key, idx)
|
||||
} else {
|
||||
key.clone()
|
||||
};
|
||||
let kv_backend = self.kv_backend.clone();
|
||||
async move {
|
||||
kv_backend
|
||||
.put(
|
||||
PutRequest::new()
|
||||
.with_key(key.into_bytes())
|
||||
.with_value(value),
|
||||
)
|
||||
.await
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
try_join_all(operations)
|
||||
let result = if self.kv_backend.capabilities().atomic_batch_put {
|
||||
self.kv_backend
|
||||
.batch_put(BatchPutRequest {
|
||||
kvs: segments.collect(),
|
||||
prev_kv: false,
|
||||
})
|
||||
.await
|
||||
.map(|_| ())
|
||||
} else {
|
||||
try_join_all(segments.map(|kv| {
|
||||
self.kv_backend
|
||||
.put(PutRequest::new().with_key(kv.key).with_value(kv.value))
|
||||
}))
|
||||
.await
|
||||
.map(|_| ())
|
||||
};
|
||||
result
|
||||
.map_err(BoxedError::new)
|
||||
.context(PutStateSnafu { key })?;
|
||||
|
||||
@@ -395,6 +392,59 @@ mod tests {
|
||||
use crate::kv_backend::etcd::EtcdStore;
|
||||
use crate::kv_backend::memory::MemoryKvBackend;
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_atomic_checkpoint_round_trip() {
|
||||
crate::kv_backend::test::check_atomic_checkpoint_round_trip(Arc::new(
|
||||
MemoryKvBackend::new(),
|
||||
))
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_atomic_segmented_put() {
|
||||
use crate::kv_backend::KvBackendCapabilities;
|
||||
use crate::kv_backend::test_util::MockKvBackendBuilder;
|
||||
|
||||
let backend = MockKvBackendBuilder::default()
|
||||
.capabilities(KvBackendCapabilities {
|
||||
atomic_batch_put: true,
|
||||
})
|
||||
.put_fn(Arc::new(|req| {
|
||||
assert_eq!(req.key, b"root/__procedure__/step");
|
||||
assert_eq!(req.value, b"ab");
|
||||
Ok(Default::default())
|
||||
}))
|
||||
.batch_put_fn(Arc::new(|req| {
|
||||
assert!(!req.prev_kv);
|
||||
let keys = req
|
||||
.kvs
|
||||
.into_iter()
|
||||
.map(|kv| (kv.key, kv.value))
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
keys,
|
||||
[
|
||||
(b"root/__procedure__/step".to_vec(), b"ab".to_vec()),
|
||||
(
|
||||
b"root/__procedure__/step/0000000001".to_vec(),
|
||||
b"cd".to_vec()
|
||||
),
|
||||
(
|
||||
b"root/__procedure__/step/0000000002".to_vec(),
|
||||
b"e".to_vec()
|
||||
),
|
||||
]
|
||||
);
|
||||
Ok(Default::default())
|
||||
}))
|
||||
.build()
|
||||
.unwrap();
|
||||
let backend = ChrootKvBackend::new(b"root".to_vec(), Arc::new(backend));
|
||||
let store = KvStateStore::new(Arc::new(backend)).with_max_value_size(Some(2));
|
||||
store.put("step", b"ab".to_vec()).await.unwrap();
|
||||
store.put("step", b"abcde".to_vec()).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_meta_state_store() {
|
||||
let store = &KvStateStore {
|
||||
|
||||
@@ -640,7 +640,13 @@ fn invalid(reason: impl Into<String>) -> DataFusionError {
|
||||
/// the previous owned key (not an Arrow buffer), timestamp, metric, and finality. An `Interleaved`
|
||||
/// chain releases that state on closure, so later fragment chains may recur with the same key,
|
||||
/// labels, and timestamps independently.
|
||||
struct SequenceValidator {
|
||||
///
|
||||
/// Both frame streams run it - [`pack_raw_series`] over what a producer publishes and
|
||||
/// [`unpack_raw_series`] over what a consumer receives - and it is reachable on its own for the one
|
||||
/// reader that has neither a frame nor a batch in between: a consumer handed the chunks in process
|
||||
/// runs exactly this check over exactly the same sequence, so the shortcut validates what the frame
|
||||
/// would have carried instead of trusting it.
|
||||
pub struct SequenceValidator {
|
||||
ordering: SeriesOrdering,
|
||||
previous_key: Option<Vec<u8>>,
|
||||
previous_timestamp: Option<i64>,
|
||||
@@ -649,7 +655,8 @@ struct SequenceValidator {
|
||||
}
|
||||
|
||||
impl SequenceValidator {
|
||||
fn new(ordering: SeriesOrdering) -> Self {
|
||||
/// A validator for a raw stream that declares `ordering`.
|
||||
pub fn new(ordering: SeriesOrdering) -> Self {
|
||||
Self {
|
||||
ordering,
|
||||
previous_key: None,
|
||||
@@ -659,14 +666,16 @@ impl SequenceValidator {
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(&self) -> datafusion_common::Result<()> {
|
||||
/// Checks that the stream ended between chains, and not inside one.
|
||||
pub fn finish(&self) -> datafusion_common::Result<()> {
|
||||
if self.previous_key.is_some() && !self.previous_is_last {
|
||||
return Err(invalid("raw series stream ended before key was final"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate(&mut self, chunk: &RawSeriesChunk) -> datafusion_common::Result<()> {
|
||||
/// Checks `chunk` against the chain this validator has read so far.
|
||||
pub fn validate(&mut self, chunk: &RawSeriesChunk) -> datafusion_common::Result<()> {
|
||||
let key = chunk.primary_key.as_slice();
|
||||
let timestamp = chunk
|
||||
.time
|
||||
@@ -732,17 +741,28 @@ impl SequenceValidator {
|
||||
/// them closes itself, so a closed chain may be followed by another chain whose labels happen to be
|
||||
/// equal. Only the still-open chain is remembered, which is what keeps such a contribution from being
|
||||
/// refused as a re-opened series while still refusing a chain that changes identity before it closes.
|
||||
struct EvaluatedSequenceValidator {
|
||||
///
|
||||
/// Like [`SequenceValidator`] it is the check both evaluated frame streams run and is reachable on
|
||||
/// its own for a consumer that is handed the chunks in process.
|
||||
pub struct EvaluatedSequenceValidator {
|
||||
/// The labels of the open chain and the last grid position it carried.
|
||||
open: Option<(SeriesLabels, usize)>,
|
||||
}
|
||||
|
||||
impl Default for EvaluatedSequenceValidator {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl EvaluatedSequenceValidator {
|
||||
fn new() -> Self {
|
||||
/// A validator with no open chain.
|
||||
pub fn new() -> Self {
|
||||
Self { open: None }
|
||||
}
|
||||
|
||||
fn finish(&self) -> datafusion_common::Result<()> {
|
||||
/// Checks that the stream ended between chains, and not inside one.
|
||||
pub fn finish(&self) -> datafusion_common::Result<()> {
|
||||
if self.open.is_some() {
|
||||
return Err(invalid(
|
||||
"evaluated series stream ended before a chain closed",
|
||||
@@ -751,7 +771,8 @@ impl EvaluatedSequenceValidator {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate(&mut self, series: &Series, is_last: bool) -> datafusion_common::Result<()> {
|
||||
/// Checks `series` against the chain this validator has read so far.
|
||||
pub fn validate(&mut self, series: &Series, is_last: bool) -> datafusion_common::Result<()> {
|
||||
let (Some(first), Some(last)) = (series.time.first_position(), series.time.last_position())
|
||||
else {
|
||||
// No carried position: only a closing chunk may be empty, and it closes the chain it
|
||||
|
||||
@@ -5,7 +5,7 @@ edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[features]
|
||||
tokio-console = ["console-subscriber", "tokio/tracing"]
|
||||
tokio-console = ["console-subscriber"]
|
||||
deadlock_detection = ["parking_lot/deadlock_detection"]
|
||||
|
||||
[lints]
|
||||
@@ -33,7 +33,6 @@ prometheus.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
snafu.workspace = true
|
||||
tokio.workspace = true
|
||||
tracing = "0.1"
|
||||
tracing-appender.workspace = true
|
||||
tracing-log = "0.2"
|
||||
|
||||
@@ -32,6 +32,7 @@ mod enter_staging;
|
||||
mod file_ref;
|
||||
mod flush_region;
|
||||
mod gc_worker;
|
||||
mod metadata_compaction;
|
||||
mod open_region;
|
||||
mod remap_manifest;
|
||||
mod sync_region;
|
||||
@@ -44,6 +45,7 @@ use crate::heartbeat::handler::enter_staging::EnterStagingRegionsHandler;
|
||||
use crate::heartbeat::handler::file_ref::{GetFileRefsHandler, GetPackedFileRefsHandler};
|
||||
use crate::heartbeat::handler::flush_region::FlushRegionsHandler;
|
||||
use crate::heartbeat::handler::gc_worker::{GcRegionsHandler, PackedGcRegionsHandler};
|
||||
use crate::heartbeat::handler::metadata_compaction::MetadataCompactionHandler;
|
||||
use crate::heartbeat::handler::open_region::OpenRegionsHandler;
|
||||
use crate::heartbeat::handler::remap_manifest::RemapManifestHandler;
|
||||
use crate::heartbeat::handler::sync_region::SyncRegionHandler;
|
||||
@@ -57,6 +59,7 @@ pub struct RegionHeartbeatResponseHandler {
|
||||
region_server: RegionServer,
|
||||
downgrade_tasks: TaskTracker<()>,
|
||||
flush_tasks: TaskTracker<()>,
|
||||
metadata_compaction: MetadataCompactionHandler,
|
||||
open_region_parallelism: usize,
|
||||
gc_tasks: TaskTracker<GcReport>,
|
||||
kv_backend: KvBackendRef,
|
||||
@@ -101,6 +104,7 @@ impl RegionHeartbeatResponseHandler {
|
||||
region_server,
|
||||
downgrade_tasks: TaskTracker::new(),
|
||||
flush_tasks: TaskTracker::new(),
|
||||
metadata_compaction: MetadataCompactionHandler::default(),
|
||||
// Default to half of the number of CPUs.
|
||||
open_region_parallelism: (num_cpus::get() / 2).max(1),
|
||||
gc_tasks: TaskTracker::new(),
|
||||
@@ -145,6 +149,9 @@ impl RegionHeartbeatResponseHandler {
|
||||
Instruction::EnterStagingRegions(_) => {
|
||||
Ok(Some(Box::new(EnterStagingRegionsHandler.into())))
|
||||
}
|
||||
Instruction::MetadataCompaction(_) => {
|
||||
Ok(Some(Box::new(self.metadata_compaction.clone().into())))
|
||||
}
|
||||
Instruction::SyncRegions(_) => Ok(Some(Box::new(SyncRegionHandler.into()))),
|
||||
Instruction::RemapManifest(_) => Ok(Some(Box::new(RemapManifestHandler.into()))),
|
||||
Instruction::ApplyStagingManifests(_) => {
|
||||
@@ -167,6 +174,7 @@ pub enum InstructionHandlers {
|
||||
GcRegions(GcRegionsHandler),
|
||||
PackedGcRegions(PackedGcRegionsHandler),
|
||||
EnterStagingRegions(EnterStagingRegionsHandler),
|
||||
MetadataCompaction(MetadataCompactionHandler),
|
||||
SyncRegions(SyncRegionHandler),
|
||||
RemapManifest(RemapManifestHandler),
|
||||
ApplyStagingManifests(ApplyStagingManifestsHandler),
|
||||
@@ -202,6 +210,7 @@ impl_from_handler!(
|
||||
GcRegionsHandler => GcRegions,
|
||||
PackedGcRegionsHandler => PackedGcRegions,
|
||||
EnterStagingRegionsHandler => EnterStagingRegions,
|
||||
MetadataCompactionHandler => MetadataCompaction,
|
||||
SyncRegionHandler => SyncRegions,
|
||||
RemapManifestHandler => RemapManifest,
|
||||
ApplyStagingManifestsHandler => ApplyStagingManifests
|
||||
@@ -252,6 +261,7 @@ dispatch_instr!(
|
||||
GcRegions => GcRegions,
|
||||
PackedGcRegions => PackedGcRegions,
|
||||
EnterStagingRegions => EnterStagingRegions,
|
||||
MetadataCompaction => MetadataCompaction,
|
||||
SyncRegions => SyncRegions,
|
||||
RemapManifest => RemapManifest,
|
||||
ApplyStagingManifests => ApplyStagingManifests,
|
||||
@@ -287,6 +297,16 @@ impl HeartbeatResponseHandler for RegionHeartbeatResponseHandler {
|
||||
to = %meta.to,
|
||||
handler = %handler.as_ref_str(),
|
||||
));
|
||||
// Apply a one-way Release before dispatching the next Pause on this stream.
|
||||
if matches!(
|
||||
&instruction,
|
||||
Instruction::MetadataCompaction(
|
||||
common_meta::instruction::MetadataCompaction::Release { .. }
|
||||
)
|
||||
) {
|
||||
handler.handle(&context, instruction).trace(span).await;
|
||||
return Ok(HandleControl::Continue);
|
||||
}
|
||||
let _handle = common_runtime::spawn_global(async move {
|
||||
let reply = handler.handle(&context, instruction).trace(span).await;
|
||||
if let Some(reply) = reply
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
// 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.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::collections::hash_map::Entry;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use common_meta::instruction::{
|
||||
InstructionError, InstructionReply, InstructionResult, MetadataCompaction, SimpleReply,
|
||||
};
|
||||
use metric_engine::engine::MetricEngine;
|
||||
use mito2::compaction::CompactionGuard;
|
||||
use store_api::storage::RegionId;
|
||||
use tokio::sync::{OnceCell, oneshot};
|
||||
use tokio::time::Instant;
|
||||
|
||||
use crate::heartbeat::handler::{HandlerContext, InstructionHandler};
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub struct MetadataCompactionHandler {
|
||||
leases: Arc<Mutex<HashMap<RegionId, PauseLease>>>,
|
||||
}
|
||||
|
||||
struct PauseLease {
|
||||
deadline: Instant,
|
||||
guard: Arc<OnceCell<CompactionGuard>>,
|
||||
cancel_expiry: oneshot::Sender<()>,
|
||||
}
|
||||
|
||||
impl MetadataCompactionHandler {
|
||||
fn lease(
|
||||
&self,
|
||||
region_id: RegionId,
|
||||
deadline: Instant,
|
||||
) -> (Arc<OnceCell<CompactionGuard>>, Instant) {
|
||||
let mut leases = self.leases.lock().unwrap();
|
||||
let lease = leases.entry(region_id).or_insert_with(|| PauseLease {
|
||||
deadline,
|
||||
guard: Arc::new(OnceCell::new()),
|
||||
cancel_expiry: self.expire_at(region_id, deadline),
|
||||
});
|
||||
if deadline > lease.deadline {
|
||||
lease.deadline = deadline;
|
||||
lease.cancel_expiry = self.expire_at(region_id, deadline);
|
||||
}
|
||||
(lease.guard.clone(), lease.deadline)
|
||||
}
|
||||
|
||||
fn expire_at(&self, region_id: RegionId, deadline: Instant) -> oneshot::Sender<()> {
|
||||
let leases = Arc::downgrade(&self.leases);
|
||||
let (cancel, cancelled) = oneshot::channel();
|
||||
common_runtime::spawn_global(async move {
|
||||
tokio::select! {
|
||||
_ = cancelled => (),
|
||||
_ = tokio::time::sleep_until(deadline) => {
|
||||
if let Some(leases) = leases.upgrade()
|
||||
&& let Entry::Occupied(entry) = leases.lock().unwrap().entry(region_id)
|
||||
&& entry.get().deadline == deadline
|
||||
{
|
||||
entry.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
cancel
|
||||
}
|
||||
|
||||
async fn pause(
|
||||
&self,
|
||||
ctx: &HandlerContext,
|
||||
region_id: RegionId,
|
||||
remaining: std::time::Duration,
|
||||
) -> InstructionResult<()> {
|
||||
let deadline = Instant::now().checked_add(remaining).ok_or_else(|| {
|
||||
InstructionError::legacy_internal_retryable("Invalid metadata sync deadline")
|
||||
})?;
|
||||
let engine = ctx
|
||||
.region_server
|
||||
.find_engine(region_id)
|
||||
.map_err(|e| InstructionError::from_error(&e))?
|
||||
.ok_or_else(|| {
|
||||
InstructionError::legacy_internal_retryable(format!(
|
||||
"Source region {region_id} is unavailable"
|
||||
))
|
||||
})?;
|
||||
let metric = engine
|
||||
.as_any()
|
||||
.downcast_ref::<MetricEngine>()
|
||||
.ok_or_else(|| {
|
||||
InstructionError::legacy_internal_retryable(format!(
|
||||
"Source region {region_id} is not a metric region"
|
||||
))
|
||||
})?;
|
||||
if ctx.region_server.is_region_leader(region_id) != Some(true) {
|
||||
return Err(InstructionError::legacy_internal_retryable(format!(
|
||||
"Source region {region_id} is not writable"
|
||||
)));
|
||||
}
|
||||
let (lease, deadline) = self.lease(region_id, deadline);
|
||||
tokio::time::timeout_at(
|
||||
deadline,
|
||||
lease.get_or_try_init(|| metric.pause_metadata_compaction(region_id)),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
InstructionError::legacy_internal_retryable(
|
||||
"Timed out pausing source metadata compaction",
|
||||
)
|
||||
})?
|
||||
.map_err(|e| InstructionError::from_error(&e))?;
|
||||
if self
|
||||
.leases
|
||||
.lock()
|
||||
.unwrap()
|
||||
.get(®ion_id)
|
||||
.is_none_or(|current| !Arc::ptr_eq(¤t.guard, &lease))
|
||||
|| Instant::now() >= deadline
|
||||
|| ctx.region_server.is_region_leader(region_id) != Some(true)
|
||||
{
|
||||
return Err(InstructionError::legacy_internal_retryable(
|
||||
"Source metadata compaction lease expired or leadership changed",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl InstructionHandler for MetadataCompactionHandler {
|
||||
type Instruction = MetadataCompaction;
|
||||
|
||||
async fn handle(
|
||||
&self,
|
||||
ctx: &HandlerContext,
|
||||
instruction: MetadataCompaction,
|
||||
) -> Option<InstructionReply> {
|
||||
match instruction {
|
||||
MetadataCompaction::Pause {
|
||||
region_id,
|
||||
remaining,
|
||||
} => {
|
||||
let result = self.pause(ctx, region_id, remaining).await;
|
||||
Some(InstructionReply::MetadataCompaction(SimpleReply {
|
||||
result: result.is_ok(),
|
||||
error: result.err(),
|
||||
}))
|
||||
}
|
||||
MetadataCompaction::Release { region_id } => {
|
||||
self.leases.lock().unwrap().remove(®ion_id);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::time::Duration;
|
||||
|
||||
use common_meta::kv_backend::memory::MemoryKvBackend;
|
||||
use mito2::test_util::{CreateRequestBuilder, TestEnv};
|
||||
use store_api::metric_engine_consts::{
|
||||
METRIC_ENGINE_NAME, METRIC_METADATA_REGION_GROUP, PHYSICAL_TABLE_METADATA_KEY,
|
||||
};
|
||||
use store_api::region_engine::RegionEngine;
|
||||
use store_api::region_request::RegionRequest;
|
||||
use store_api::storage::RegionId;
|
||||
|
||||
use super::*;
|
||||
use crate::tests::mock_region_server;
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_metadata_pause_renews_and_expires() {
|
||||
let mut env = TestEnv::with_prefix("metadata-compaction-lease").await;
|
||||
let mito = env.create_engine(Default::default()).await;
|
||||
let mut server = mock_region_server();
|
||||
let metric = MetricEngine::try_new(mito.clone(), Default::default()).unwrap();
|
||||
server.register_engine(Arc::new(metric));
|
||||
let region_id = RegionId::new(32, 1);
|
||||
let mut create = CreateRequestBuilder::new()
|
||||
.tag_num(0)
|
||||
.insert_option(PHYSICAL_TABLE_METADATA_KEY, "")
|
||||
.build();
|
||||
create.engine = METRIC_ENGINE_NAME.to_string();
|
||||
create.column_metadatas[0].column_schema.name = "greptime_value".into();
|
||||
create.column_metadatas[1].column_schema.name = "greptime_timestamp".into();
|
||||
server
|
||||
.handle_request(region_id, RegionRequest::Create(create))
|
||||
.await
|
||||
.unwrap();
|
||||
let ctx = HandlerContext::new_for_test(server, Arc::new(MemoryKvBackend::new()));
|
||||
let handler = MetadataCompactionHandler::default();
|
||||
handler
|
||||
.pause(&ctx, region_id, Duration::from_secs(30))
|
||||
.await
|
||||
.unwrap();
|
||||
let first_deadline = handler.leases.lock().unwrap()[®ion_id].deadline;
|
||||
handler
|
||||
.pause(&ctx, region_id, Duration::from_secs(60))
|
||||
.await
|
||||
.unwrap();
|
||||
let renewed = handler.leases.lock().unwrap()[®ion_id].deadline;
|
||||
assert!(renewed > first_deadline);
|
||||
handler
|
||||
.pause(&ctx, region_id, Duration::from_secs(1))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(handler.leases.lock().unwrap()[®ion_id].deadline, renewed);
|
||||
let meta = RegionId::with_group_and_seq(32, METRIC_METADATA_REGION_GROUP, 1);
|
||||
let compact = || mito.handle_request(meta, RegionRequest::Compact(Default::default()));
|
||||
let err = compact().await.unwrap_err();
|
||||
assert!(matches!(
|
||||
err.into_inner()
|
||||
.as_any()
|
||||
.downcast_ref::<mito2::error::Error>(),
|
||||
Some(mito2::error::Error::CompactionCancelled { .. })
|
||||
));
|
||||
mito.handle_request(region_id, RegionRequest::Compact(Default::default()))
|
||||
.await
|
||||
.unwrap();
|
||||
mito.handle_request(meta, RegionRequest::Flush(Default::default()))
|
||||
.await
|
||||
.unwrap();
|
||||
handler
|
||||
.handle(&ctx, MetadataCompaction::Release { region_id })
|
||||
.await;
|
||||
compact().await.unwrap();
|
||||
handler
|
||||
.pause(&ctx, region_id, Duration::from_millis(200))
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(compact().await.is_err());
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
while handler.leases.lock().unwrap().contains_key(®ion_id) {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
compact().await.unwrap();
|
||||
}
|
||||
}
|
||||
@@ -101,7 +101,9 @@ impl UpgradeRegionsHandler {
|
||||
let mut timeout = None;
|
||||
|
||||
for upgrade_region in upgrade_regions {
|
||||
let Some(writable) = ctx.region_server.is_region_leader(upgrade_region.region_id)
|
||||
let Some(confirmed) = ctx
|
||||
.region_server
|
||||
.is_confirmed_leader(upgrade_region.region_id)
|
||||
else {
|
||||
// Region is not found.
|
||||
debug!("Region {} is not found", upgrade_region.region_id);
|
||||
@@ -114,8 +116,10 @@ impl UpgradeRegionsHandler {
|
||||
continue;
|
||||
};
|
||||
|
||||
// Ignores the catchup requests for writable regions.
|
||||
if writable {
|
||||
// Ignores the catchup requests for writable regions, except those a catchup made
|
||||
// writable with no Leader lease since: they may lack what the leader has written
|
||||
// since, and the engine catches them up again.
|
||||
if confirmed {
|
||||
warn!(
|
||||
"Region {} is writable, ignores the catchup request",
|
||||
upgrade_region.region_id
|
||||
@@ -226,6 +230,7 @@ mod tests {
|
||||
use common_meta::kv_backend::memory::MemoryKvBackend;
|
||||
use mito2::engine::MITO_ENGINE_NAME;
|
||||
use store_api::region_engine::RegionRole;
|
||||
use store_api::region_request::RegionRequest;
|
||||
use store_api::storage::RegionId;
|
||||
|
||||
use crate::error;
|
||||
@@ -361,6 +366,38 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_writable_region_awaiting_leader_lease_catches_up() {
|
||||
let mock_region_server = mock_region_server();
|
||||
let region_id = RegionId::new(1024, 1);
|
||||
|
||||
let (mock_engine, mut requests) =
|
||||
MockRegionEngine::with_custom_apply_fn(MITO_ENGINE_NAME, |region_engine| {
|
||||
region_engine.mock_role = Some(Some(RegionRole::Leader));
|
||||
region_engine.mock_confirmed_leader = Some(false);
|
||||
});
|
||||
mock_region_server.register_test_region(region_id, mock_engine);
|
||||
let kv_backend = Arc::new(MemoryKvBackend::new());
|
||||
let handler_context = HandlerContext::new_for_test(mock_region_server, kv_backend);
|
||||
let reply = UpgradeRegionsHandler::new_test()
|
||||
.handle(
|
||||
&handler_context,
|
||||
vec![UpgradeRegion {
|
||||
region_id,
|
||||
replay_timeout: Duration::from_secs(1),
|
||||
..Default::default()
|
||||
}],
|
||||
)
|
||||
.await;
|
||||
|
||||
let reply = &reply.unwrap().expect_upgrade_regions_reply()[0];
|
||||
assert!(reply.ready);
|
||||
assert!(reply.error.is_none());
|
||||
let (caught_up, request) = requests.try_recv().unwrap();
|
||||
assert_eq!(caught_up, region_id);
|
||||
assert!(matches!(request, RegionRequest::Catchup(_)));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_region_not_ready() {
|
||||
let mock_region_server = mock_region_server();
|
||||
|
||||
@@ -478,6 +478,14 @@ impl RegionServer {
|
||||
})
|
||||
}
|
||||
|
||||
/// See [`RegionEngine::is_confirmed_leader`](store_api::region_engine::RegionEngine::is_confirmed_leader).
|
||||
pub fn is_confirmed_leader(&self, region_id: RegionId) -> Option<bool> {
|
||||
self.inner
|
||||
.region_map
|
||||
.get(®ion_id)
|
||||
.and_then(|engine| engine.is_confirmed_leader(region_id))
|
||||
}
|
||||
|
||||
pub fn set_region_role(&self, region_id: RegionId, role: RegionRole) -> Result<()> {
|
||||
let engine = self
|
||||
.inner
|
||||
@@ -491,7 +499,8 @@ impl RegionServer {
|
||||
|
||||
/// Sets the role of a region from a lease the metasrv grants until `deadline`, in reply to a
|
||||
/// heartbeat sent at `sent_at`. Returns false if the engine ignores a Leader lease because the
|
||||
/// region was downgraded or (re)opened after `sent_at`.
|
||||
/// region was downgraded or (re)opened after `sent_at`, a catchup runs on it, or it waits for a
|
||||
/// reload.
|
||||
pub fn set_region_role_with_lease(
|
||||
&self,
|
||||
region_id: RegionId,
|
||||
|
||||
@@ -135,6 +135,7 @@ pub struct MockRegionEngine {
|
||||
pub(crate) handle_sync_region_mock_fn: Option<MockSyncRegionHandler>,
|
||||
pub(crate) handle_stop_mock_fn: Option<MockStopHandler>,
|
||||
pub(crate) mock_role: Option<Option<RegionRole>>,
|
||||
pub(crate) mock_confirmed_leader: Option<bool>,
|
||||
/// The candidate lease ids of the leases the engine received.
|
||||
pub(crate) candidate_lease_ids: Mutex<Vec<Option<u64>>>,
|
||||
engine: String,
|
||||
@@ -154,6 +155,7 @@ impl MockRegionEngine {
|
||||
handle_sync_region_mock_fn: None,
|
||||
handle_stop_mock_fn: None,
|
||||
mock_role: None,
|
||||
mock_confirmed_leader: None,
|
||||
candidate_lease_ids: Mutex::default(),
|
||||
engine: engine.to_string(),
|
||||
}),
|
||||
@@ -177,6 +179,7 @@ impl MockRegionEngine {
|
||||
handle_sync_region_mock_fn: None,
|
||||
handle_stop_mock_fn: None,
|
||||
mock_role: None,
|
||||
mock_confirmed_leader: None,
|
||||
candidate_lease_ids: Mutex::default(),
|
||||
engine: engine.to_string(),
|
||||
}),
|
||||
@@ -200,6 +203,7 @@ impl MockRegionEngine {
|
||||
handle_sync_region_mock_fn: None,
|
||||
handle_stop_mock_fn: None,
|
||||
mock_role: None,
|
||||
mock_confirmed_leader: None,
|
||||
candidate_lease_ids: Mutex::default(),
|
||||
engine: engine.to_string(),
|
||||
}),
|
||||
@@ -224,6 +228,7 @@ impl MockRegionEngine {
|
||||
handle_sync_region_mock_fn: None,
|
||||
handle_stop_mock_fn: None,
|
||||
mock_role: None,
|
||||
mock_confirmed_leader: None,
|
||||
candidate_lease_ids: Mutex::default(),
|
||||
engine: engine.to_string(),
|
||||
};
|
||||
@@ -330,6 +335,13 @@ impl RegionEngine for MockRegionEngine {
|
||||
Some(RegionRole::Leader)
|
||||
}
|
||||
|
||||
fn is_confirmed_leader(&self, region_id: RegionId) -> Option<bool> {
|
||||
self.role(region_id).map(|role| {
|
||||
self.mock_confirmed_leader
|
||||
.unwrap_or(role != RegionRole::Follower)
|
||||
})
|
||||
}
|
||||
|
||||
async fn sync_region(
|
||||
&self,
|
||||
region_id: RegionId,
|
||||
|
||||
+306
-153
@@ -1853,6 +1853,167 @@ fn compact_histogram(values: &HistogramSamples) -> Result<(ArrayRef, UInt32Array
|
||||
Ok((table, UInt32Array::from(remapped)))
|
||||
}
|
||||
|
||||
/// The `fields` column of a state frame: one list per row, one item per carried position.
|
||||
///
|
||||
/// A state frame's per-field list carries one item per grid position the row holds, and an item is
|
||||
/// absent exactly where that field has no contribution at that position. The absence lives on the
|
||||
/// item - the child struct's validity - not on the list's own validity, which is per row: a row
|
||||
/// always has a list, with zero or more items in it.
|
||||
///
|
||||
/// One encoder builds this column, so a state frame and a state row handed over in process are the
|
||||
/// same bytes: [`StateFrameRow::from_state_series`] calls it for a single group, and the frame
|
||||
/// encoder calls it for the rows it is about to write.
|
||||
fn encode_state_fields(field_types: &Fields, rows: &[FrameRow]) -> Result<StructArray> {
|
||||
// A state frame's per-field list carries one item per grid position the row holds, and an
|
||||
// item is absent exactly where that field has no contribution at that position. The
|
||||
// absence lives on the item — the child struct's validity — not on the list's own
|
||||
// validity, which is per row: a row always has a list, with zero or more items in it.
|
||||
let count = rows.len();
|
||||
let mut field_arrays: Vec<ArrayRef> = Vec::with_capacity(field_types.len());
|
||||
for (index, field) in field_types.iter().enumerate() {
|
||||
let mut lengths = Vec::with_capacity(count);
|
||||
let mut positions = 0usize;
|
||||
for row in rows {
|
||||
let RowPayload::States(fields) = &row.payload else {
|
||||
return invalid_series("state frame row carries sample payload");
|
||||
};
|
||||
let values = fields
|
||||
.get(index)
|
||||
.ok_or_else(|| err("state field count mismatch"))?;
|
||||
if values.len() != row.time.len()? {
|
||||
return invalid_series("state list length mismatch");
|
||||
}
|
||||
lengths.push(values.len());
|
||||
positions = add_checked(positions, values.len())?;
|
||||
}
|
||||
|
||||
let item = match field.data_type() {
|
||||
DataType::List(item) => item,
|
||||
_ => return invalid_series("state field schema mismatch"),
|
||||
};
|
||||
let DataType::Struct(components) = item.data_type() else {
|
||||
return invalid_series("state list item is not a component struct");
|
||||
};
|
||||
// Absence lives on the item, so the child struct's validity is one flag per position.
|
||||
// A row of a state frame always carries states; a caller that hands in the wrong payload
|
||||
// is refused here rather than panicking inside an iterator.
|
||||
let mut present = Vec::with_capacity(positions);
|
||||
for row in rows {
|
||||
let RowPayload::States(fields) = &row.payload else {
|
||||
return invalid_series("state frame row carries sample payload");
|
||||
};
|
||||
present.extend(fields[index].iter().map(Option::is_some));
|
||||
}
|
||||
debug_assert_eq!(present.len(), positions);
|
||||
|
||||
// Every component of a field is absent at exactly the same positions - the field's own -
|
||||
// so they share the one mask, which the child struct already needs.
|
||||
let nulls = present
|
||||
.iter()
|
||||
.any(|present| !present)
|
||||
.then(|| NullBuffer::from(present.clone()));
|
||||
// A column's name is the component it declares, so each array is built by reading that
|
||||
// component off the payload; a payload that does not keep it is refused rather than
|
||||
// written as a zero.
|
||||
let arrays: Vec<ArrayRef> = components
|
||||
.iter()
|
||||
.map(|component| {
|
||||
let declared = StateComponent::parse(component.name())?;
|
||||
let array: ArrayRef = match declared {
|
||||
StateComponent::HistogramValue | StateComponent::HistogramCompensation => {
|
||||
// One histogram per position, so one batch carries the whole column. An
|
||||
// absent position holds an empty placeholder whose value the shared mask
|
||||
// makes unreadable, exactly as a null float slot holds a zero.
|
||||
let mut histograms = HistogramBatchBuilder::new();
|
||||
for row in rows {
|
||||
for state in state_field(row, index)? {
|
||||
let Some(state) = state else {
|
||||
histograms.push(empty_histogram())?;
|
||||
continue;
|
||||
};
|
||||
let histogram = state
|
||||
.histogram_component(declared)
|
||||
.ok_or_else(missing_state_component)?;
|
||||
if histogram.len() != 1 {
|
||||
return invalid_series(
|
||||
"a histogram state component carries exactly one histogram",
|
||||
);
|
||||
}
|
||||
let view = histogram.view(0).ok_or_else(missing_state_component)?;
|
||||
histograms.push(view)?;
|
||||
}
|
||||
}
|
||||
let batch = histograms.finish()?;
|
||||
Arc::new(
|
||||
StructArray::try_new(
|
||||
histogram_fields(),
|
||||
batch.as_arrow().columns().to_vec(),
|
||||
nulls.clone(),
|
||||
)
|
||||
.map_err(|error| err(error.to_string()))?,
|
||||
) as ArrayRef
|
||||
}
|
||||
StateComponent::Value
|
||||
| StateComponent::Mean
|
||||
| StateComponent::Compensation
|
||||
| StateComponent::Count => {
|
||||
let mut floats = Vec::with_capacity(positions);
|
||||
for row in rows {
|
||||
for state in state_field(row, index)? {
|
||||
// A missing position's value is unreadable, so it holds the same
|
||||
// zero a null slot has always held here.
|
||||
floats.push(match state {
|
||||
None => 0.0,
|
||||
Some(state) => state
|
||||
.float_component(declared)
|
||||
.ok_or_else(missing_state_component)?,
|
||||
});
|
||||
}
|
||||
}
|
||||
Arc::new(Float64Array::new(ScalarBuffer::from(floats), nulls.clone()))
|
||||
}
|
||||
_ => {
|
||||
let mut booleans = Vec::with_capacity(positions);
|
||||
for row in rows {
|
||||
for state in state_field(row, index)? {
|
||||
booleans.push(match state {
|
||||
None => false,
|
||||
Some(state) => state
|
||||
.bool_component(declared)
|
||||
.ok_or_else(missing_state_component)?,
|
||||
});
|
||||
}
|
||||
}
|
||||
Arc::new(BooleanArray::new(
|
||||
BooleanBuffer::from(booleans),
|
||||
nulls.clone(),
|
||||
))
|
||||
}
|
||||
};
|
||||
Ok(array)
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
|
||||
let child = if components.is_empty() {
|
||||
Arc::new(StructArray::new_empty_fields(
|
||||
positions,
|
||||
Some(NullBuffer::from(present)),
|
||||
)) as ArrayRef
|
||||
} else {
|
||||
Arc::new(
|
||||
StructArray::try_new(components.clone(), arrays, Some(NullBuffer::from(present)))
|
||||
.map_err(|error| err(error.to_string()))?,
|
||||
) as ArrayRef
|
||||
};
|
||||
// The list itself is valid for every row: absence is an absent item, never an absent
|
||||
// list, so a reader can tell "this field holds nothing here" from "this row has no
|
||||
// list at all".
|
||||
let list = list_array(&lengths, child, item.as_ref().clone(), None)?;
|
||||
field_arrays.push(Arc::new(list) as ArrayRef);
|
||||
}
|
||||
struct_array(field_types.clone(), field_arrays)
|
||||
}
|
||||
|
||||
/// Encodes buffered rows as one batch with direct N-row Arrow array construction.
|
||||
///
|
||||
/// Each histogram segment carries each *distinct* table row it references exactly once, and its
|
||||
@@ -1938,159 +2099,7 @@ fn encode_rows(schema: &SchemaRef, shape: FrameShape, rows: &[FrameRow]) -> Resu
|
||||
};
|
||||
|
||||
if shape.content == FrameContent::AggregateState {
|
||||
// A state frame's per-field list carries one item per grid position the row holds, and an
|
||||
// item is absent exactly where that field has no contribution at that position. The
|
||||
// absence lives on the item — the child struct's validity — not on the list's own
|
||||
// validity, which is per row: a row always has a list, with zero or more items in it.
|
||||
let mut field_arrays: Vec<ArrayRef> = Vec::with_capacity(field_types.len());
|
||||
for (index, field) in field_types.iter().enumerate() {
|
||||
let mut lengths = Vec::with_capacity(count);
|
||||
let mut positions = 0usize;
|
||||
for row in rows {
|
||||
let RowPayload::States(fields) = &row.payload else {
|
||||
return invalid_series("state frame row carries sample payload");
|
||||
};
|
||||
let values = fields
|
||||
.get(index)
|
||||
.ok_or_else(|| err("state field count mismatch"))?;
|
||||
if values.len() != row.time.len()? {
|
||||
return invalid_series("state list length mismatch");
|
||||
}
|
||||
lengths.push(values.len());
|
||||
positions = add_checked(positions, values.len())?;
|
||||
}
|
||||
|
||||
let item = match field.data_type() {
|
||||
DataType::List(item) => item,
|
||||
_ => return invalid_series("state field schema mismatch"),
|
||||
};
|
||||
let DataType::Struct(components) = item.data_type() else {
|
||||
return invalid_series("state list item is not a component struct");
|
||||
};
|
||||
// Absence lives on the item, so the child struct's validity is one flag per position.
|
||||
// A row of a state frame always carries states; a caller that hands in the wrong payload
|
||||
// is refused here rather than panicking inside an iterator.
|
||||
let mut present = Vec::with_capacity(positions);
|
||||
for row in rows {
|
||||
let RowPayload::States(fields) = &row.payload else {
|
||||
return invalid_series("state frame row carries sample payload");
|
||||
};
|
||||
present.extend(fields[index].iter().map(Option::is_some));
|
||||
}
|
||||
debug_assert_eq!(present.len(), positions);
|
||||
|
||||
// Every component of a field is absent at exactly the same positions - the field's own -
|
||||
// so they share the one mask, which the child struct already needs.
|
||||
let nulls = present
|
||||
.iter()
|
||||
.any(|present| !present)
|
||||
.then(|| NullBuffer::from(present.clone()));
|
||||
// A column's name is the component it declares, so each array is built by reading that
|
||||
// component off the payload; a payload that does not keep it is refused rather than
|
||||
// written as a zero.
|
||||
let arrays: Vec<ArrayRef> = components
|
||||
.iter()
|
||||
.map(|component| {
|
||||
let declared = StateComponent::parse(component.name())?;
|
||||
let array: ArrayRef = match declared {
|
||||
StateComponent::HistogramValue | StateComponent::HistogramCompensation => {
|
||||
// One histogram per position, so one batch carries the whole column. An
|
||||
// absent position holds an empty placeholder whose value the shared mask
|
||||
// makes unreadable, exactly as a null float slot holds a zero.
|
||||
let mut histograms = HistogramBatchBuilder::new();
|
||||
for row in rows {
|
||||
for state in state_field(row, index)? {
|
||||
let Some(state) = state else {
|
||||
histograms.push(empty_histogram())?;
|
||||
continue;
|
||||
};
|
||||
let histogram = state
|
||||
.histogram_component(declared)
|
||||
.ok_or_else(missing_state_component)?;
|
||||
if histogram.len() != 1 {
|
||||
return invalid_series(
|
||||
"a histogram state component carries exactly one histogram",
|
||||
);
|
||||
}
|
||||
let view = histogram
|
||||
.view(0)
|
||||
.ok_or_else(missing_state_component)?;
|
||||
histograms.push(view)?;
|
||||
}
|
||||
}
|
||||
let batch = histograms.finish()?;
|
||||
Arc::new(
|
||||
StructArray::try_new(
|
||||
histogram_fields(),
|
||||
batch.as_arrow().columns().to_vec(),
|
||||
nulls.clone(),
|
||||
)
|
||||
.map_err(|error| err(error.to_string()))?,
|
||||
) as ArrayRef
|
||||
}
|
||||
StateComponent::Value
|
||||
| StateComponent::Mean
|
||||
| StateComponent::Compensation
|
||||
| StateComponent::Count => {
|
||||
let mut floats = Vec::with_capacity(positions);
|
||||
for row in rows {
|
||||
for state in state_field(row, index)? {
|
||||
// A missing position's value is unreadable, so it holds the same
|
||||
// zero a null slot has always held here.
|
||||
floats.push(match state {
|
||||
None => 0.0,
|
||||
Some(state) => state
|
||||
.float_component(declared)
|
||||
.ok_or_else(missing_state_component)?,
|
||||
});
|
||||
}
|
||||
}
|
||||
Arc::new(Float64Array::new(ScalarBuffer::from(floats), nulls.clone()))
|
||||
}
|
||||
_ => {
|
||||
let mut booleans = Vec::with_capacity(positions);
|
||||
for row in rows {
|
||||
for state in state_field(row, index)? {
|
||||
booleans.push(match state {
|
||||
None => false,
|
||||
Some(state) => state
|
||||
.bool_component(declared)
|
||||
.ok_or_else(missing_state_component)?,
|
||||
});
|
||||
}
|
||||
}
|
||||
Arc::new(BooleanArray::new(
|
||||
BooleanBuffer::from(booleans),
|
||||
nulls.clone(),
|
||||
))
|
||||
}
|
||||
};
|
||||
Ok(array)
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
|
||||
let child = if components.is_empty() {
|
||||
Arc::new(StructArray::new_empty_fields(
|
||||
positions,
|
||||
Some(NullBuffer::from(present)),
|
||||
)) as ArrayRef
|
||||
} else {
|
||||
Arc::new(
|
||||
StructArray::try_new(
|
||||
components.clone(),
|
||||
arrays,
|
||||
Some(NullBuffer::from(present)),
|
||||
)
|
||||
.map_err(|error| err(error.to_string()))?,
|
||||
) as ArrayRef
|
||||
};
|
||||
// The list itself is valid for every row: absence is an absent item, never an absent
|
||||
// list, so a reader can tell "this field holds nothing here" from "this row has no
|
||||
// list at all".
|
||||
let list = list_array(&lengths, child, item.as_ref().clone(), None)?;
|
||||
field_arrays.push(Arc::new(list) as ArrayRef);
|
||||
}
|
||||
let fields = struct_array(field_types.clone(), field_arrays)?;
|
||||
let fields = encode_state_fields(field_types, rows)?;
|
||||
return assemble_frame_batch(schema, shape, rows, time, fields);
|
||||
}
|
||||
let mut empty_table: Option<ArrayRef> = None;
|
||||
@@ -2440,7 +2449,151 @@ pub struct StateFrameRow {
|
||||
state: AggregateStateSchema,
|
||||
}
|
||||
|
||||
/// The Arrow layout the state rows of one publication are encoded against.
|
||||
///
|
||||
/// Building a row needs three things that depend on the state layout and the series it is of rather
|
||||
/// than on the group: the `fields` column's item struct, the components each item carries, and the
|
||||
/// grid the positions are on. Resolving them once makes a group cost its own encoding and nothing
|
||||
/// else, which is what a consumer merging the groups of one publication wants.
|
||||
///
|
||||
/// One constructor builds every row of every group ([`StateRowLayout::row`]), so a producer that
|
||||
/// hands a row over in process and a frame a boundary reads cannot disagree about what a row is.
|
||||
pub struct StateRowLayout {
|
||||
/// The layout every row is validated against, and the one its fields encode.
|
||||
state: AggregateStateSchema,
|
||||
/// How many series fields a row carries.
|
||||
fields: usize,
|
||||
/// The grid a row's positions are on.
|
||||
grid: Arc<EvalGrid>,
|
||||
/// The `fields` column's item struct, resolved from the frame schema once.
|
||||
field_types: Fields,
|
||||
}
|
||||
|
||||
impl StateRowLayout {
|
||||
/// The layout `schema`'s export declares, as the rows of its groups are built against it.
|
||||
///
|
||||
/// `state` is the layout the export declares: it is checked against itself once here, so a
|
||||
/// layout no row could encode is refused before any group is built against it.
|
||||
pub fn try_new(state: &AggregateStateSchema, schema: &SeriesSchema) -> Result<Self> {
|
||||
let grid = schema
|
||||
.eval_grid
|
||||
.clone()
|
||||
.ok_or_else(|| err("an aggregate state chunk needs an evaluation grid"))?;
|
||||
let state = AggregateStateSchema::try_new(state.kind, state.components.to_vec())?;
|
||||
let frame_schema = aggregate_state_frame_schema(&state, schema, FrameLabelMode::Explicit)?;
|
||||
let DataType::Struct(field_types) = frame_schema.field(3).data_type() else {
|
||||
return invalid_series("fields schema mismatch");
|
||||
};
|
||||
Ok(Self {
|
||||
state,
|
||||
fields: schema.fields.len(),
|
||||
grid,
|
||||
field_types: field_types.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
/// One producer group as the state row a consumer merges.
|
||||
///
|
||||
/// The group already is the row: field-major state on sparse absolute positions, the labels it
|
||||
/// was folded under, and whether it closes its chain. What the group must also be is a row of
|
||||
/// this layout: its positions on this grid, its field count the series', and every position it
|
||||
/// carries a contribution from at least one field. Those are checked here rather than where the
|
||||
/// row is consumed, so a row that exists is a row a merge can read - exactly what the frame
|
||||
/// decoder checks of a decoded frame row.
|
||||
pub fn row(&self, series: StateSeries, is_last: bool) -> Result<StateFrameRow> {
|
||||
if series.states.len() != self.fields
|
||||
|| series
|
||||
.states
|
||||
.iter()
|
||||
.any(|field| field.len() != series.time.len())
|
||||
{
|
||||
return invalid_series("aggregate state fields do not match the carried positions");
|
||||
}
|
||||
// A position is addressed on the grid this layout declares: a group folded on another grid
|
||||
// would name positions this node's merge does not have.
|
||||
if !series
|
||||
.time
|
||||
.grid()
|
||||
.is_some_and(|grid| grid.spec() == self.grid.spec())
|
||||
{
|
||||
return invalid_series("aggregate state positions are not on the series grid");
|
||||
}
|
||||
let spans = series
|
||||
.time
|
||||
.runs()
|
||||
.map(|run| GridSpan::new(run.position, run.len))
|
||||
.collect::<Vec<_>>();
|
||||
let axis = TimeAxis::from_grid_spans(Arc::clone(&self.grid), spans)?;
|
||||
let row = FrameRow {
|
||||
key: None,
|
||||
metric: Some(series.metric.clone()),
|
||||
is_last,
|
||||
time: RowTime::Spans(
|
||||
axis.runs()
|
||||
.map(|run| GridSpan::new(run.position, run.len))
|
||||
.collect(),
|
||||
),
|
||||
payload: RowPayload::States(series.states),
|
||||
bytes: 0,
|
||||
};
|
||||
let fields = encode_state_fields(&self.field_types, std::slice::from_ref(&row))?;
|
||||
// The row is checked against the layout it declares, so a consumer that merges it reads the
|
||||
// components this producer wrote and nothing else - the same check the frame decoder makes.
|
||||
let validated = StateFieldsBatch::try_from_arrow(fields.clone(), &self.state)?;
|
||||
if validated.len() != self.fields {
|
||||
return invalid_series("aggregate state field count mismatch");
|
||||
}
|
||||
for field in 0..validated.len() {
|
||||
let items = validated
|
||||
.field(field)
|
||||
.ok_or_else(|| err("null state field list"))?;
|
||||
if items.len() != axis.len() {
|
||||
return invalid_series("state list length does not match carried positions");
|
||||
}
|
||||
}
|
||||
// A carried position exists because a field has a contribution there; one no field carries
|
||||
// is a position the merge would have to invent a state for, so it is refused here.
|
||||
for position in 0..axis.len() {
|
||||
let mut present = false;
|
||||
for field in 0..validated.len() {
|
||||
present |= validated.is_present(field, position)?;
|
||||
}
|
||||
if !present {
|
||||
return invalid_series("aggregate state names a position with no contribution");
|
||||
}
|
||||
}
|
||||
Ok(StateFrameRow {
|
||||
metric: series.metric,
|
||||
time: axis,
|
||||
is_last,
|
||||
fields,
|
||||
state: self.state.clone(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl StateFrameRow {
|
||||
/// One producer group as the state row a consumer merges.
|
||||
///
|
||||
/// The group already is the row: field-major state on sparse absolute positions, the labels it
|
||||
/// was folded under, and whether it closes its chain. Building it here is what lets a producer
|
||||
/// hand the row over in process instead of packing a frame and decoding it back, and it is the
|
||||
/// same construction the frame encoder uses ([`encode_state_fields`]), so the two readings of
|
||||
/// one export cannot disagree.
|
||||
///
|
||||
/// `state` is the layout the export declares and `schema` the series it is of: both are checked
|
||||
/// against the group before anything is built, exactly as the frame decoder checks them against
|
||||
/// the frame it reads. Building many groups of one export is what [`StateRowLayout`] is for; this
|
||||
/// is that layout resolved for one row.
|
||||
pub fn from_state_series(
|
||||
state: &AggregateStateSchema,
|
||||
schema: &SeriesSchema,
|
||||
series: StateSeries,
|
||||
is_last: bool,
|
||||
) -> Result<Self> {
|
||||
StateRowLayout::try_new(state, schema)?.row(series, is_last)
|
||||
}
|
||||
|
||||
/// Complete group identity for this row.
|
||||
pub fn metric(&self) -> &SeriesLabels {
|
||||
&self.metric
|
||||
|
||||
@@ -4773,6 +4773,168 @@ mod aggregate_state_acceptance {
|
||||
(batch, decoder)
|
||||
}
|
||||
|
||||
/// The row a producer builds is the row the frame it would have written carries.
|
||||
///
|
||||
/// One encoder builds both: `from_state_series` for the single group a consumer merges in
|
||||
/// process, and the frame encoder for the columns a boundary consumer decodes. So the labels,
|
||||
/// the carried positions, the finality and every component value have to be identical - which is
|
||||
/// what makes handing the row over a saving rather than a second semantics.
|
||||
#[test]
|
||||
fn a_state_row_is_the_row_the_frame_carries() {
|
||||
let schema = state_schema(&["v"], 3);
|
||||
let state = AggregateStateSchema::try_new(
|
||||
Kind::Sum,
|
||||
vec![Component::Value, Component::Compensation],
|
||||
)
|
||||
.unwrap();
|
||||
let series = StateSeries {
|
||||
metric: metric(Some("m"), &[("job", "x")]),
|
||||
time: TimeAxis::from_grid_spans(
|
||||
schema.eval_grid.clone().unwrap(),
|
||||
vec![GridSpan::new(0, 2), GridSpan::new(2, 1)],
|
||||
)
|
||||
.unwrap(),
|
||||
states: vec![values(3, 1.0)],
|
||||
};
|
||||
let direct =
|
||||
StateFrameRow::from_state_series(&state, &schema, series.clone(), true).unwrap();
|
||||
|
||||
let (batch, decoder) = state_frame(
|
||||
Kind::Sum,
|
||||
&schema,
|
||||
vec![GridSpan::new(0, 2), GridSpan::new(2, 1)],
|
||||
series.states.clone(),
|
||||
true,
|
||||
);
|
||||
let framed = decoder.decode_aggregate_state(&batch).unwrap();
|
||||
assert_eq!(1, framed.len(), "one group is one row");
|
||||
let framed = &framed[0];
|
||||
|
||||
assert_eq!(direct.metric(), framed.metric());
|
||||
assert_eq!(direct.is_last(), framed.is_last());
|
||||
assert_eq!(
|
||||
direct.time().positions().collect::<Vec<_>>(),
|
||||
framed.time().positions().collect::<Vec<_>>(),
|
||||
"the same positions, in the same order"
|
||||
);
|
||||
let built = direct.fields().unwrap();
|
||||
let decoded = framed.fields().unwrap();
|
||||
assert_eq!(built.kind(), decoded.kind());
|
||||
assert_eq!(built.components(), decoded.components());
|
||||
assert_eq!(built.len(), decoded.len(), "the same fields");
|
||||
for field in 0..built.len() {
|
||||
let items = built.field(field).expect("the field is present");
|
||||
for position in 0..items.len() {
|
||||
assert_eq!(
|
||||
built.is_present(field, position).unwrap(),
|
||||
decoded.is_present(field, position).unwrap(),
|
||||
"field {field} at {position} is present on both"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
built.field_values(field, Component::Value).unwrap(),
|
||||
decoded.field_values(field, Component::Value).unwrap(),
|
||||
"field {field} carries the same values"
|
||||
);
|
||||
assert_eq!(
|
||||
built.field_values(field, Component::Compensation).unwrap(),
|
||||
decoded
|
||||
.field_values(field, Component::Compensation)
|
||||
.unwrap(),
|
||||
"field {field} carries the same compensations"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A group whose positions are on another grid is refused where the row is built.
|
||||
///
|
||||
/// A row addresses positions on the grid its export declares; one folded on a different grid
|
||||
/// names positions that grid does not have, so a merge reading it would either drop the
|
||||
/// contribution or read another point's. The frame decoder never meets such a row - it builds
|
||||
/// every axis on the grid the frame declares - so the in-process construction is where the
|
||||
/// claim has to be checked, once, instead of at the merge.
|
||||
#[test]
|
||||
fn a_state_row_refuses_positions_on_another_grid() {
|
||||
let schema = state_schema(&["v"], 3);
|
||||
let state = AggregateStateSchema::try_new(
|
||||
Kind::Sum,
|
||||
vec![Component::Value, Component::Compensation],
|
||||
)
|
||||
.unwrap();
|
||||
let other_grid = Arc::new(
|
||||
crate::series::time::EvalGrid::try_new(
|
||||
crate::series::time::GridSpec::try_new(0, 2, 3).unwrap(),
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
let series = StateSeries {
|
||||
metric: metric(Some("m"), &[("job", "x")]),
|
||||
time: TimeAxis::from_grid_spans(other_grid, vec![GridSpan::new(0, 1)]).unwrap(),
|
||||
states: vec![values(1, 1.0)],
|
||||
};
|
||||
let error = match StateFrameRow::from_state_series(&state, &schema, series, true) {
|
||||
Ok(_) => panic!("a group on another grid is not a row of this export"),
|
||||
Err(error) => error,
|
||||
};
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("aggregate state positions are not on the series grid"),
|
||||
"{error}"
|
||||
);
|
||||
}
|
||||
|
||||
/// A carried position no field contributes to is refused where the row is built.
|
||||
///
|
||||
/// A position exists because a field has a contribution there: an all-absent one is a position
|
||||
/// the merge would have to invent a state for, which is the same refusal `merge_row` makes of a
|
||||
/// decoded row. Checking it here means both readings of one export refuse it in the same place,
|
||||
/// before any row exists to merge.
|
||||
#[test]
|
||||
fn a_state_row_refuses_a_position_no_field_carries() {
|
||||
let schema = state_schema(&["v"], 2);
|
||||
let state = AggregateStateSchema::try_new(
|
||||
Kind::Sum,
|
||||
vec![Component::Value, Component::Compensation],
|
||||
)
|
||||
.unwrap();
|
||||
let mut states = values(2, 1.0);
|
||||
states[1] = None;
|
||||
let series = StateSeries {
|
||||
metric: metric(Some("m"), &[("job", "x")]),
|
||||
time: TimeAxis::from_grid_spans(
|
||||
schema.eval_grid.clone().unwrap(),
|
||||
vec![GridSpan::new(0, 2)],
|
||||
)
|
||||
.unwrap(),
|
||||
states: vec![states],
|
||||
};
|
||||
let error = match StateFrameRow::from_state_series(&state, &schema, series, true) {
|
||||
Ok(_) => panic!("a position no field carries is not a row of this export"),
|
||||
Err(error) => error,
|
||||
};
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("aggregate state names a position with no contribution"),
|
||||
"{error}"
|
||||
);
|
||||
|
||||
// The same group with a contribution at that position is a row.
|
||||
let series = StateSeries {
|
||||
metric: metric(Some("m"), &[("job", "x")]),
|
||||
time: TimeAxis::from_grid_spans(
|
||||
schema.eval_grid.clone().unwrap(),
|
||||
vec![GridSpan::new(0, 2)],
|
||||
)
|
||||
.unwrap(),
|
||||
states: vec![values(2, 1.0)],
|
||||
};
|
||||
let row = StateFrameRow::from_state_series(&state, &schema, series, true)
|
||||
.expect("a contribution at every carried position is a row");
|
||||
assert_eq!(2, row.time().len());
|
||||
}
|
||||
|
||||
fn floats(n: usize, seed: f64) -> Vec<Option<Values>> {
|
||||
(0..n)
|
||||
.map(|i| {
|
||||
|
||||
@@ -148,19 +148,41 @@ impl EvalGrid {
|
||||
self.timestamps.get_or_try_init(|| {
|
||||
let len = usize::try_from(self.spec.len)
|
||||
.map_err(|_| invalid_series("grid length overflows usize"))?;
|
||||
let mut values = Vec::new();
|
||||
values
|
||||
.try_reserve_exact(len)
|
||||
.map_err(|_| invalid_series("grid timestamp allocation failed"))?;
|
||||
for index in 0..len {
|
||||
let timestamp =
|
||||
(self.spec.start_ms as i128) + (index as i128) * (self.spec.step_ms as i128);
|
||||
values.push(timestamp as i64);
|
||||
}
|
||||
Ok(values.into())
|
||||
Ok(self.gather_timestamps(0, len)?.into())
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the whole timestamp array exists already.
|
||||
///
|
||||
/// A consumer that pays for the array -- an execution reserving what it is about to allocate --
|
||||
/// asks this before it materializes a grid: a grid that is already materialized was charged to
|
||||
/// whoever materialized it, and a second consumer must not charge it again.
|
||||
pub fn is_materialized(&self) -> bool {
|
||||
self.timestamps.get().is_some()
|
||||
}
|
||||
|
||||
/// Returns the timestamps of the positions `start..start + len` as an array of their own,
|
||||
/// leaving the grid unmaterialized.
|
||||
///
|
||||
/// Every value is [`Self::timestamp_at`]'s, in position order, so gathering a window of the
|
||||
/// grid costs its own length and not the length of the grid it is cut from.
|
||||
fn gather_timestamps(&self, start: usize, len: usize) -> Result<Vec<i64>> {
|
||||
let mut values = Vec::new();
|
||||
values
|
||||
.try_reserve_exact(len)
|
||||
.map_err(|_| invalid_series("grid timestamp allocation failed"))?;
|
||||
let end = start.checked_add(len).context(InvalidSeriesSnafu {
|
||||
reason: "grid range overflow".to_string(),
|
||||
})?;
|
||||
for position in start..end {
|
||||
let Some(timestamp) = self.timestamp_at(position) else {
|
||||
return invalid("grid range exceeds its grid");
|
||||
};
|
||||
values.push(timestamp);
|
||||
}
|
||||
Ok(values)
|
||||
}
|
||||
|
||||
fn timestamp_at(&self, position: usize) -> Option<i64> {
|
||||
if position as u64 >= self.spec.len {
|
||||
return None;
|
||||
@@ -211,9 +233,22 @@ impl GridRange {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.len == 0
|
||||
}
|
||||
/// Returns this range as a zero-copy Arrow buffer slice.
|
||||
/// Returns the timestamps of the positions this range names.
|
||||
///
|
||||
/// A range covering the whole grid shares the grid's array, which that grid has to materialize
|
||||
/// for any reader of all of it. A range cut out of a larger grid computes the `len` timestamps
|
||||
/// it names instead, each one [`EvalGrid::timestamp_at`]'s for its position: reading a window
|
||||
/// out of a large grid costs the window's rows, and leaves a deferred grid deferred.
|
||||
pub fn timestamps(&self) -> Result<ScalarBuffer<i64>> {
|
||||
Ok(self.grid.timestamps()?.slice(self.start, self.len))
|
||||
if self.covers_grid() {
|
||||
return Ok(self.grid.timestamps()?.clone());
|
||||
}
|
||||
Ok(self.grid.gather_timestamps(self.start, self.len)?.into())
|
||||
}
|
||||
|
||||
/// Whether this range names every position of its grid.
|
||||
fn covers_grid(&self) -> bool {
|
||||
self.start == 0 && u64::try_from(self.len).is_ok_and(|len| len == self.grid.spec.len)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -809,13 +844,20 @@ impl TimeAxis {
|
||||
|
||||
/// Returns the timestamps of the carried rows, in compact-row order.
|
||||
///
|
||||
/// A single-run grid axis lends its buffer without copying; an axis of several runs, and a
|
||||
/// chunked explicit axis, allocate one array of the carried rows.
|
||||
/// An axis covering the whole grid lends the grid's array; a grid axis holding fewer positions
|
||||
/// than its grid computes the rows it carries and lends nothing, so gathering a window out of
|
||||
/// a large grid costs the window and leaves a deferred grid deferred. An axis of several runs,
|
||||
/// and a chunked explicit axis, allocate one array of the carried rows.
|
||||
pub fn timestamps(&self) -> Result<Cow<'_, [i64]>> {
|
||||
match self {
|
||||
Self::Grid(range) => Ok(Cow::Borrowed(
|
||||
&range.grid.timestamps()?[range.start()..range.start() + range.len()],
|
||||
)),
|
||||
Self::Grid(range) => {
|
||||
if !range.covers_grid() {
|
||||
return Ok(Cow::Owned(
|
||||
range.grid.gather_timestamps(range.start(), range.len())?,
|
||||
));
|
||||
}
|
||||
Ok(Cow::Borrowed(&range.grid.timestamps()?[..]))
|
||||
}
|
||||
Self::GridRanges(ranges) => {
|
||||
let mut timestamps = Vec::with_capacity(ranges.len());
|
||||
for (position, _) in self.positions() {
|
||||
|
||||
@@ -118,11 +118,67 @@ fn deferred_grid_allocation_failure_is_reported_and_not_cached() {
|
||||
Arc::new(EvalGrid::try_deferred(GridSpec::try_new(i64::MIN, 1, len).unwrap()).unwrap());
|
||||
assert!(grid.timestamps().is_err());
|
||||
assert!(grid.timestamps.get().is_none());
|
||||
let range = GridRange::try_new(grid.clone(), 0, 1).unwrap();
|
||||
assert!(range.timestamps().is_err());
|
||||
assert!(TimeAxis::Grid(range).timestamps().is_err());
|
||||
// A range naming every point of that grid asks for the array that does not fit, and the
|
||||
// failure is still the series error rather than an abort.
|
||||
let whole = GridRange::try_new(grid.clone(), 0, len as usize).unwrap();
|
||||
assert!(whole.timestamps().is_err());
|
||||
assert!(TimeAxis::Grid(whole).timestamps().is_err());
|
||||
assert!(grid.timestamps().is_err());
|
||||
assert!(grid.timestamps.get().is_none());
|
||||
// A range that is nearly the whole grid gathers its own rows, and its allocation fails too:
|
||||
// the gathered array is the range's, so the failure is reported rather than aborted.
|
||||
let nearly = GridRange::try_new(grid.clone(), 0, len as usize - 1).unwrap();
|
||||
assert!(nearly.timestamps().is_err());
|
||||
assert!(TimeAxis::Grid(nearly).timestamps().is_err());
|
||||
assert!(grid.timestamps.get().is_none());
|
||||
}
|
||||
|
||||
/// A window cut out of a large grid computes the rows it names instead of materializing the grid.
|
||||
///
|
||||
/// The gathered values are the grid's own points, so a subrange reads the same timestamps it did
|
||||
/// when it was a slice of the whole array; what changes is the cost, which is the window's rows
|
||||
/// and no longer the grid's.
|
||||
#[test]
|
||||
fn subrange_timestamps_gather_only_the_rows_they_name() {
|
||||
let len = (isize::MAX as u64 / std::mem::size_of::<i64>() as u64) + 1;
|
||||
let grid = Arc::new(EvalGrid::try_deferred(GridSpec::try_new(-5, 2, len).unwrap()).unwrap());
|
||||
let range = GridRange::try_new(grid.clone(), 7, 3).unwrap();
|
||||
assert!(!grid.is_materialized());
|
||||
let gathered = range.timestamps().unwrap();
|
||||
assert_eq!(&gathered[..], &[9, 11, 13]);
|
||||
let axis = TimeAxis::Grid(range);
|
||||
let axis_timestamps = axis.timestamps().unwrap();
|
||||
assert_eq!(axis_timestamps.as_ref(), &[9, 11, 13]);
|
||||
// Every gathered point is what the axis answers for the row holding it.
|
||||
for (row, timestamp) in axis_timestamps.iter().enumerate() {
|
||||
assert_eq!(*timestamp, axis.timestamp(row).unwrap());
|
||||
}
|
||||
assert!(
|
||||
!grid.is_materialized(),
|
||||
"the subrange materialized its grid"
|
||||
);
|
||||
|
||||
// A range naming the whole grid still shares the grid's one array.
|
||||
let small = Arc::new(EvalGrid::try_deferred(GridSpec::try_new(10, 10, 4).unwrap()).unwrap());
|
||||
let all = GridRange::try_new(small.clone(), 0, 4).unwrap();
|
||||
assert!(!small.is_materialized());
|
||||
let shared = all.timestamps().unwrap();
|
||||
assert!(
|
||||
small.is_materialized(),
|
||||
"the whole-grid range did not materialize the grid it shares"
|
||||
);
|
||||
assert_eq!(shared.as_ptr(), small.timestamps().unwrap().as_ptr());
|
||||
assert_eq!(
|
||||
TimeAxis::Grid(all).timestamps().unwrap().as_ref(),
|
||||
&[10, 20, 30, 40]
|
||||
);
|
||||
|
||||
// An empty range at the end of a grid has no row to gather and materializes nothing.
|
||||
let grid = Arc::new(EvalGrid::try_deferred(GridSpec::try_new(0, 1, 3).unwrap()).unwrap());
|
||||
let empty = GridRange::try_new(grid.clone(), 3, 0).unwrap();
|
||||
assert!(empty.timestamps().unwrap().is_empty());
|
||||
assert!(TimeAxis::Grid(empty).timestamps().unwrap().is_empty());
|
||||
assert!(!grid.is_materialized());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -167,11 +223,20 @@ fn grid_materialization_revalidates_public_specs_and_shares_ranges_by_value() {
|
||||
let b = GridRange::try_new(Arc::new(EvalGrid::try_new(grid.spec()).unwrap()), 1, 3).unwrap();
|
||||
assert_eq!(a, b);
|
||||
let values = a.timestamps().unwrap();
|
||||
assert_eq!(
|
||||
// A subrange computes its own rows rather than slicing the grid's array, which it no longer
|
||||
// shares: what it answers is still the grid's points, one per position it names.
|
||||
assert_ne!(
|
||||
values.as_ptr(),
|
||||
grid.timestamps().unwrap().as_ptr().wrapping_add(1)
|
||||
grid.timestamps().unwrap().as_ptr().wrapping_add(1),
|
||||
"the subrange borrowed the grid's array"
|
||||
);
|
||||
assert_eq!(&values[..], &[-2, 1, 4]);
|
||||
let whole = GridRange::try_new(grid.clone(), 0, 5).unwrap();
|
||||
assert_eq!(
|
||||
whole.timestamps().unwrap().as_ptr(),
|
||||
grid.timestamps().unwrap().as_ptr(),
|
||||
"a whole-grid range copied the array it could share"
|
||||
);
|
||||
assert!(GridRange::try_new(grid.clone(), 5, 0).unwrap().is_empty());
|
||||
assert!(GridRange::try_new(grid.clone(), 4, 2).is_err());
|
||||
assert!(GridRange::try_new(grid, usize::MAX, 1).is_err());
|
||||
|
||||
@@ -442,6 +442,21 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_json_rejects_integers_out_of_range() {
|
||||
for input in [
|
||||
"18446744073709551616",
|
||||
"-9223372036854775809",
|
||||
r#"{"n": 123456789012345678901234567890}"#,
|
||||
] {
|
||||
assert!(parse_string_to_jsonb(input).is_err(), "{input}");
|
||||
}
|
||||
for input in ["18446744073709551615", "-9223372036854775808"] {
|
||||
let jsonb = parse_string_to_jsonb(input).unwrap();
|
||||
assert_eq!(jsonb_to_string(&jsonb).unwrap(), input);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_v2_jsonb_to_serde_json_escaped_keys()
|
||||
-> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||
|
||||
@@ -260,8 +260,7 @@ macro_rules! impl_validity_for_vector {
|
||||
macro_rules! impl_get_for_vector {
|
||||
($array: expr, $index: ident) => {
|
||||
if $array.is_valid($index) {
|
||||
// Safety: The index have been checked by `is_valid()`.
|
||||
unsafe { $array.value_unchecked($index).into() }
|
||||
$array.value($index).into()
|
||||
} else {
|
||||
Value::Null
|
||||
}
|
||||
@@ -271,8 +270,7 @@ macro_rules! impl_get_for_vector {
|
||||
macro_rules! impl_get_ref_for_vector {
|
||||
($array: expr, $index: ident) => {
|
||||
if $array.is_valid($index) {
|
||||
// Safety: The index have been checked by `is_valid()`.
|
||||
unsafe { $array.value_unchecked($index).into() }
|
||||
$array.value($index).into()
|
||||
} else {
|
||||
ValueRef::Null
|
||||
}
|
||||
|
||||
@@ -138,8 +138,7 @@ impl Decimal128Vector {
|
||||
/// Get decimal128 Value from array by index.
|
||||
fn get_decimal128_value_from_array(&self, index: usize) -> Option<Decimal128> {
|
||||
if self.array.is_valid(index) {
|
||||
// Safety: The index have been checked by `is_valid()`.
|
||||
let value = unsafe { self.array.value_unchecked(index) };
|
||||
let value = self.array.value(index);
|
||||
// Safety: The precision and scale have been checked by Vector.
|
||||
Some(Decimal128::new(value, self.precision(), self.scale()))
|
||||
} else {
|
||||
|
||||
@@ -164,8 +164,7 @@ impl<T: LogicalPrimitiveType> Vector for PrimitiveVector<T> {
|
||||
|
||||
fn get(&self, index: usize) -> Value {
|
||||
if self.array.is_valid(index) {
|
||||
// Safety: The index have been checked by `is_valid()`.
|
||||
let wrapper = unsafe { T::Wrapper::from_native(self.array.value_unchecked(index)) };
|
||||
let wrapper = T::Wrapper::from_native(self.array.value(index));
|
||||
wrapper.into()
|
||||
} else {
|
||||
Value::Null
|
||||
@@ -174,8 +173,7 @@ impl<T: LogicalPrimitiveType> Vector for PrimitiveVector<T> {
|
||||
|
||||
fn get_ref(&self, index: usize) -> ValueRef<'_> {
|
||||
if self.array.is_valid(index) {
|
||||
// Safety: The index have been checked by `is_valid()`.
|
||||
let wrapper = unsafe { T::Wrapper::from_native(self.array.value_unchecked(index)) };
|
||||
let wrapper = T::Wrapper::from_native(self.array.value(index));
|
||||
wrapper.into()
|
||||
} else {
|
||||
ValueRef::Null
|
||||
@@ -416,6 +414,13 @@ mod tests {
|
||||
assert_eq!(&ArrowDataType::Int32, arrow_arr.data_type());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "Trying to access an element at index")]
|
||||
fn test_get_out_of_bounds_without_nulls_panics() {
|
||||
let vector = Int32Vector::from_slice([1]);
|
||||
vector.get(1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_from_values() {
|
||||
let v = Int32Vector::from_values(vec![1, 2, 3, 4]);
|
||||
|
||||
@@ -523,6 +523,13 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "Trying to access an element at index")]
|
||||
fn test_get_ref_out_of_bounds_without_nulls_panics() {
|
||||
let vector = StringVector::from(vec!["a"]);
|
||||
vector.get_ref(1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_string_vector_build_get() {
|
||||
let mut builder = StringVectorBuilder::with_capacity(4);
|
||||
|
||||
@@ -474,6 +474,8 @@ impl ObjectStoreLogStore {
|
||||
durable_reclaim_boundary: reclaim_boundary,
|
||||
unindexed: unindexed.into_iter().chain(moved_past).collect(),
|
||||
pending_releases: BTreeMap::new(),
|
||||
handoff_waiters: Vec::new(),
|
||||
deferred_handoffs: HashMap::new(),
|
||||
release_retry: RetryBackoff::default(),
|
||||
release_retry_logged_at: None,
|
||||
creating: HashSet::new(),
|
||||
@@ -1326,6 +1328,58 @@ impl LogStore for ObjectStoreLogStore {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Raises the sequence of the next object above the object that holds
|
||||
/// the bound, the larger of `entry_id` and the largest id of the region in
|
||||
/// the objects the store opened with or issued since it opened, sealing
|
||||
/// the open batch first if it holds ids under the current sequence.
|
||||
/// Returns the bound once a release record of the region's current
|
||||
/// watermark is durable and indexed in an object at or above that
|
||||
/// sequence. A store opened later takes its next sequence from that
|
||||
/// object, and the watermark does not move. The record joins the next
|
||||
/// sealed batch, so hand-offs within one flush interval share an object.
|
||||
///
|
||||
/// In the `enqueued` mode a bound at or below an id the store already
|
||||
/// assigned the region needs no raised sequence, as that mode never
|
||||
/// assigns an id twice: the record may then share the object of that id,
|
||||
/// and every later id of the region is above it.
|
||||
///
|
||||
/// A store that is failing or lacks I/O permission keeps the raised
|
||||
/// sequence and the record and fails the call with a retryable error; the
|
||||
/// record is written with a later batch. Other errors are as the object
|
||||
/// store reports them. If the open batch holds ids under the floor and
|
||||
/// cannot be sealed, the floor and the record wait for that seal instead,
|
||||
/// unless the store stops first.
|
||||
///
|
||||
/// The wait usually ends with the next periodic seal. It is longer while
|
||||
/// the object store returns errors: in the `enqueued` mode the create is
|
||||
/// repeated until it succeeds, and in the `durable` mode a seal that only
|
||||
/// carries records waits for the backoff of earlier rollbacks. A hand-off
|
||||
/// pending when stop begins gets the outcome of the object that carries
|
||||
/// its record, which is stop's last object if its record was not yet
|
||||
/// sealed into a batch. In the `durable` mode, one whose record was in a
|
||||
/// sealed batch whose create had not started fails as stopped, and stop
|
||||
/// writes the record into its last object.
|
||||
async fn handoff(&self, provider: &Provider, entry_id: EntryId) -> Result<EntryId> {
|
||||
let region_id = self.region_of(provider)?;
|
||||
let (response_tx, response_rx) = oneshot::channel();
|
||||
self.command_tx
|
||||
.send(Command::Handoff {
|
||||
region_id,
|
||||
entry_id,
|
||||
response: response_tx,
|
||||
})
|
||||
.await
|
||||
.ok()
|
||||
.context(ObjectStoreWalStoppedSnafu)?;
|
||||
let (bound, persisted) = response_rx
|
||||
.await
|
||||
.ok()
|
||||
.context(ObjectStoreWalStoppedSnafu)??;
|
||||
persisted.await.ok().context(ObjectStoreWalStoppedSnafu)??;
|
||||
self.start_region_history(provider)?;
|
||||
Ok(bound)
|
||||
}
|
||||
|
||||
async fn read_node(
|
||||
&self,
|
||||
node_id: u64,
|
||||
@@ -1372,6 +1426,13 @@ enum Command {
|
||||
full: bool,
|
||||
response: oneshot::Sender<Result<()>>,
|
||||
},
|
||||
/// Answered with the bound and a receiver of the outcome of the object
|
||||
/// that carries the release record, see [`Actor::handle_handoff`].
|
||||
Handoff {
|
||||
region_id: RegionId,
|
||||
entry_id: EntryId,
|
||||
response: oneshot::Sender<Result<(EntryId, oneshot::Receiver<Result<()>>)>>,
|
||||
},
|
||||
/// Answered once the actor has accepted the bounded release for its next
|
||||
/// batch. Unlike `Release`, this does not wait for persistence.
|
||||
ReleaseEntries {
|
||||
@@ -1560,9 +1621,9 @@ impl Failing {
|
||||
/// | --- | --- | --- | --- |
|
||||
/// | created, or identical retry | advances | acknowledged in order | healthy |
|
||||
/// | transient error, `durable` mode | never reused: a create that reported an error may have written its object | every batch that is not indexed fails, created ones included; retries are assigned new ids | healthy: the next batch links to the last indexed object, so no chain reaches a failed batch; retained releases back off before a release-only retry |
|
||||
/// | transient error, `enqueued` mode | unchanged | already acknowledged, except a permanent release, which waits for the repeat | healthy: the create is repeated with the same bytes after [`CREATE_RETRY_DELAY`], which an identical retry accepts |
|
||||
/// | error that requires intervention, `enqueued` mode | unchanged | already acknowledged, except a permanent release, which fails while its record stays in the backlog; later appends and permanent releases are rejected with a retryable error | failing, see [`Failing`]: the lowest pending create is repeated alone with backoff, and the first create that succeeds ends it |
|
||||
/// | object store error, `enqueued` mode after `stop` began | never reused | already acknowledged, except a permanent release, which fails with the stopped error | the backlog is dropped and `stop` reports the error |
|
||||
/// | transient error, `enqueued` mode | unchanged | already acknowledged, except a permanent release or a hand-off, which waits for the repeat | healthy: the create is repeated with the same bytes after [`CREATE_RETRY_DELAY`], which an identical retry accepts |
|
||||
/// | error that requires intervention, `enqueued` mode | unchanged | already acknowledged, except a permanent release or a hand-off, which fails while its record stays in the backlog; later appends, permanent releases and hand-offs are rejected with a retryable error | failing, see [`Failing`]: the lowest pending create is repeated alone with backoff, and the first create that succeeds ends it |
|
||||
/// | object store error, `enqueued` mode after `stop` began | never reused | already acknowledged, except a permanent release or a hand-off, which fails with the stopped error | the backlog is dropped and `stop` reports the error |
|
||||
/// | an object of an earlier epoch holds the sequence, `durable` mode | never reused | as for a transient error | healthy: that object can never be on the chain |
|
||||
/// | an object of the same or a later epoch holds the sequence, any conflicting object in the `enqueued` mode, encoding or catalog error | unchanged | every batch that is not indexed fails | poisoned |
|
||||
/// | created at the last representable sequence | cannot advance | acknowledged | poisoned: no later batch can be allocated a sequence |
|
||||
@@ -1656,6 +1717,15 @@ struct Actor {
|
||||
/// region for the next sealed batch. Timer ticks seal them when no entries
|
||||
/// arrive, after any durable rollback backoff; shutdown drains them in both modes.
|
||||
pending_releases: BTreeMap<RegionId, EntryId>,
|
||||
/// Callers of a hand-off whose record is in `pending_releases`; the next
|
||||
/// sealed batch carries them.
|
||||
handoff_waiters: Vec<oneshot::Sender<Result<()>>>,
|
||||
/// Regions and bounds of hand-offs that found the open batch holding ids
|
||||
/// under a sequence their floor must pass and could not seal it, keeping
|
||||
/// the largest bound of each region. Once it is sealed, the floors move
|
||||
/// and the next batch carries their records, unless the store stops
|
||||
/// first: a stopped store assigns no ids, and their hand-offs failed.
|
||||
deferred_handoffs: HashMap<RegionId, EntryId>,
|
||||
/// Backoff for release-only sealing after a durable rollback retains records.
|
||||
release_retry: RetryBackoff,
|
||||
/// Last warning about retained release records after a durable rollback.
|
||||
@@ -1730,6 +1800,10 @@ impl Actor {
|
||||
Some(Command::Release { region_id, full, response }) => {
|
||||
self.handle_release(region_id, full, response);
|
||||
}
|
||||
Some(Command::Handoff { region_id, entry_id, response }) => {
|
||||
let result = self.handle_handoff(region_id, entry_id);
|
||||
let _ = response.send(result);
|
||||
}
|
||||
Some(Command::ReleaseEntries { region_id, entry_id, response }) => {
|
||||
let result = self.handle_release_entries(region_id, entry_id);
|
||||
let _ = response.send(result);
|
||||
@@ -2023,11 +2097,19 @@ impl Actor {
|
||||
sealed_at: Instant::now(),
|
||||
attempts: 0,
|
||||
waiters: std::mem::take(&mut self.pending),
|
||||
release_waiters: Vec::new(),
|
||||
// Their records were pending, so the batch carries them.
|
||||
release_waiters: std::mem::take(&mut self.handoff_waiters),
|
||||
#[cfg(any(test, feature = "testing"))]
|
||||
seal_waiters: Vec::new(),
|
||||
state: CreateState::Pending,
|
||||
});
|
||||
// The open batch is sealed, so the deferred floors can move, and a
|
||||
// later batch carries their records.
|
||||
for (region_id, bound) in std::mem::take(&mut self.deferred_handoffs) {
|
||||
if matches!(self.raise_sequence_floor(region_id, bound), Ok(true)) {
|
||||
self.keep_watermark_record(region_id);
|
||||
}
|
||||
}
|
||||
self.start_creates();
|
||||
true
|
||||
}
|
||||
@@ -2271,10 +2353,13 @@ impl Actor {
|
||||
}
|
||||
// So would a release. Its record stays in the backlog and becomes
|
||||
// durable with it.
|
||||
for batch in &mut self.sealed {
|
||||
for waiter in batch.release_waiters.drain(..) {
|
||||
let _ = waiter.send(Err(failing.reject()));
|
||||
}
|
||||
for waiter in self
|
||||
.sealed
|
||||
.iter_mut()
|
||||
.flat_map(|batch| batch.release_waiters.drain(..))
|
||||
.chain(self.handoff_waiters.drain(..))
|
||||
{
|
||||
let _ = waiter.send(Err(failing.reject()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2520,7 +2605,8 @@ impl Actor {
|
||||
self.fail_waiters(error);
|
||||
}
|
||||
|
||||
/// Fails the waiters of the open batch and the durability waiters.
|
||||
/// Fails the waiters of the open batch, the durability waiters and the
|
||||
/// hand-offs whose records are pending; the records stay pending.
|
||||
fn fail_waiters(&mut self, error: impl Fn() -> Error) {
|
||||
for pending in self.pending.drain(..) {
|
||||
let _ = pending.response.send(Err(error()));
|
||||
@@ -2528,6 +2614,9 @@ impl Actor {
|
||||
for waiter in self.durable_waiters.drain(..) {
|
||||
let _ = waiter.response.send(Err(error()));
|
||||
}
|
||||
for waiter in self.handoff_waiters.drain(..) {
|
||||
let _ = waiter.send(Err(error()));
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_wait_durable(
|
||||
@@ -2704,6 +2793,63 @@ impl Actor {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Handles [`ObjectStoreLogStore::handoff`], see there: returns the bound
|
||||
/// and a receiver answered with the outcome of the batch that carries the
|
||||
/// release record.
|
||||
fn handle_handoff(
|
||||
&mut self,
|
||||
region_id: RegionId,
|
||||
entry_id: EntryId,
|
||||
) -> Result<(EntryId, oneshot::Receiver<Result<()>>)> {
|
||||
let bound = entry_id.max(self.issued_entry_ids.get(®ion_id).copied().unwrap_or(0));
|
||||
// Stop, then a terminal error, are checked only by the raise, so a
|
||||
// hand-off handled after stop began fails as stopped.
|
||||
match self.raise_sequence_floor(region_id, bound) {
|
||||
Ok(raised) => ensure!(raised, ObjectStoreWalStoppedSnafu),
|
||||
Err(Error::WalObjectSequenceUnsettled { .. }) => {
|
||||
// A `durable` store without I/O permission rolls the open
|
||||
// batch back, so the floor can move now; the `enqueued` mode
|
||||
// keeps the batch, and the floor waits for its seal.
|
||||
if !self.flush_open_batch() && !self.open_batch.is_empty() {
|
||||
let deferred = self.deferred_handoffs.entry(region_id).or_default();
|
||||
*deferred = (*deferred).max(bound);
|
||||
return ObjectStoreWalLeaseExpiredSnafu.fail();
|
||||
}
|
||||
ensure!(
|
||||
self.raise_sequence_floor(region_id, bound)?,
|
||||
ObjectStoreWalStoppedSnafu
|
||||
);
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
self.keep_watermark_record(region_id);
|
||||
if let Some(failing) = &mut self.failing {
|
||||
return Err(failing.reject());
|
||||
}
|
||||
ensure!(self.io_allowed(), ObjectStoreWalLeaseExpiredSnafu);
|
||||
let (response, receiver) = oneshot::channel();
|
||||
// A caller that stopped waiting leaves a closed response behind.
|
||||
self.handoff_waiters.retain(|waiter| !waiter.is_closed());
|
||||
self.handoff_waiters.push(response);
|
||||
Ok((bound, receiver))
|
||||
}
|
||||
|
||||
/// Keeps a release record of the region's current watermark, or of 0
|
||||
/// without one, for the next sealed batch.
|
||||
fn keep_watermark_record(&mut self, region_id: RegionId) {
|
||||
let watermark = self
|
||||
.obsolete_entry_ids
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.get(®ion_id)
|
||||
.copied()
|
||||
.unwrap_or(0);
|
||||
self.keep_release(Release {
|
||||
region_id,
|
||||
entry_id: watermark,
|
||||
});
|
||||
}
|
||||
|
||||
/// Moves the watermark of the region up to the release and seals the
|
||||
/// open batch with a release record of the region; `response` is
|
||||
/// answered once that object is durable and indexed. The batch carries
|
||||
@@ -2898,10 +3044,11 @@ impl Actor {
|
||||
/// `entry_id` unless it is there already. The move fails while the open
|
||||
/// batch has handed out ids under the next sequence. A floor that does
|
||||
/// not fit an entry id poisons the store like an exhausted sequence.
|
||||
fn raise_sequence_floor(&mut self, region_id: RegionId, entry_id: EntryId) -> Result<()> {
|
||||
// Nothing is assigned an id after stop began.
|
||||
/// Returns false if stop began, which leaves the floor where it is, as
|
||||
/// nothing is assigned an id any more.
|
||||
fn raise_sequence_floor(&mut self, region_id: RegionId, entry_id: EntryId) -> Result<bool> {
|
||||
if self.is_stopped() {
|
||||
return Ok(());
|
||||
return Ok(false);
|
||||
}
|
||||
if let Some(error) = terminal(&self.terminal_error) {
|
||||
return Err(shared(&error));
|
||||
@@ -2914,14 +3061,14 @@ impl Actor {
|
||||
if self.ack_mode == AckMode::Enqueued
|
||||
&& entry_id <= self.issued_entry_ids.get(®ion_id).copied().unwrap_or(0)
|
||||
{
|
||||
return Ok(());
|
||||
return Ok(true);
|
||||
}
|
||||
let sequence_floor = sequence_floor(entry_id);
|
||||
let Some(next_object_seq) = self.next_object_seq else {
|
||||
return Ok(());
|
||||
return Ok(true);
|
||||
};
|
||||
if next_object_seq >= sequence_floor {
|
||||
return Ok(());
|
||||
return Ok(true);
|
||||
}
|
||||
ensure!(
|
||||
self.open_batch.is_empty(),
|
||||
@@ -2931,7 +3078,7 @@ impl Actor {
|
||||
);
|
||||
if sequence_floor < OBJECT_SEQ_LIMIT {
|
||||
self.next_object_seq = Some(sequence_floor);
|
||||
Ok(())
|
||||
Ok(true)
|
||||
} else {
|
||||
self.next_object_seq = None;
|
||||
let error = self.poison(
|
||||
@@ -4127,6 +4274,18 @@ mod tests {
|
||||
tokio::spawn(async move { store.append_batch(entries).await })
|
||||
}
|
||||
|
||||
/// Waits until `count` hand-offs wait for the object that carries their
|
||||
/// records.
|
||||
async fn wait_for_handoff_waiters(store: &ObjectStoreLogStore, count: usize) {
|
||||
timeout(WAIT, async {
|
||||
while inspect_actor(store, |actor| actor.handoff_waiters.len()).await < count {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// Appends `count` single-entry batches, waiting for each to be admitted
|
||||
/// before the next is sent, so they are admitted in order.
|
||||
async fn spawn_appends(
|
||||
@@ -10585,6 +10744,542 @@ mod tests {
|
||||
store.stop().await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_store_handoff_raises_ids_above_the_bound_and_keeps_the_watermark() {
|
||||
let _serialized = SERIALIZED.lock().await;
|
||||
let object_store = memory_store();
|
||||
let config = config(MIN_FLUSH_INTERVAL, u64::MAX);
|
||||
let store = open(object_store.clone(), &config).await;
|
||||
let one = region(1);
|
||||
let first = append(&store, one, "a1").await.unwrap().last_entry_ids[&one];
|
||||
assert_eq!(id(1, 1), first);
|
||||
|
||||
// A bound below the ids issued for the region hands it over too.
|
||||
store.handoff(&provider(one), 0).await.unwrap();
|
||||
// A larger bound moves the next sequence past its object, and the
|
||||
// object carrying the record is the first at that sequence. The record
|
||||
// keeps the region's watermark, which it has none of.
|
||||
let bound = id(5, 3);
|
||||
store.handoff(&provider(one), bound).await.unwrap();
|
||||
assert_eq!(
|
||||
vec![release(one, 0)],
|
||||
releases_of(store.io.as_ref(), 6).await
|
||||
);
|
||||
assert_eq!(None, watermark(&store, one));
|
||||
assert_eq!(
|
||||
expected_entries(one, &[(first, "a1")]),
|
||||
read_entries(&store, one, 0).await
|
||||
);
|
||||
store.stop().await.unwrap();
|
||||
assert!(matches!(
|
||||
store.handoff(&provider(one), bound).await,
|
||||
Err(Error::ObjectStoreWalStopped { .. })
|
||||
));
|
||||
|
||||
// A store opened later, whose newest object is the record's, holds
|
||||
// the history through the bound, assigns ids above it and still reads
|
||||
// the region's entries.
|
||||
let store = open(object_store, &config).await;
|
||||
assert_eq!(None, missing_history(&store, one, bound).await);
|
||||
let next = append(&store, one, "a3").await.unwrap().last_entry_ids[&one];
|
||||
assert!(next > bound, "{next} is not above {bound}");
|
||||
assert_eq!(first, read_entries(&store, one, 0).await[0].entry_id());
|
||||
store.stop().await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_store_handoff_records_the_current_watermark_of_the_region() {
|
||||
let _serialized = SERIALIZED.lock().await;
|
||||
let store = open(memory_store(), &config(MIN_FLUSH_INTERVAL, u64::MAX)).await;
|
||||
let one = region(1);
|
||||
let first = append(&store, one, "a1").await.unwrap().last_entry_ids[&one];
|
||||
let second = append(&store, one, "a2").await.unwrap().last_entry_ids[&one];
|
||||
store.obsolete(&provider(one), one, first).await.unwrap();
|
||||
assert_eq!(Some(first), watermark(&store, one));
|
||||
|
||||
// Each hand-off records the watermark, not its bound, and the entry
|
||||
// above the watermark stays readable.
|
||||
let bound = id(5, 3);
|
||||
store.handoff(&provider(one), bound).await.unwrap();
|
||||
assert_eq!(
|
||||
vec![release(one, first)],
|
||||
releases_of(store.io.as_ref(), 6).await
|
||||
);
|
||||
let bound = id(7, 1);
|
||||
store.handoff(&provider(one), bound).await.unwrap();
|
||||
assert_eq!(
|
||||
vec![release(one, first)],
|
||||
releases_of(store.io.as_ref(), 8).await
|
||||
);
|
||||
assert_eq!(Some(first), watermark(&store, one));
|
||||
assert_eq!(
|
||||
expected_entries(one, &[(second, "a2")]),
|
||||
read_entries(&store, one, 0).await
|
||||
);
|
||||
store.stop().await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_store_handoff_admitted_after_stop_began_keeps_nothing() {
|
||||
let _serialized = SERIALIZED.lock().await;
|
||||
for poisoned in [false, true] {
|
||||
let store = open(memory_store(), &manual()).await;
|
||||
let one = region(1);
|
||||
// Stop sets its flag before the actor handles a command, so a
|
||||
// hand-off the actor handles after that fails as stopped, also on a
|
||||
// poisoned store, and keeps no floor, record or waiter.
|
||||
let (stopped, next_object_seq, records, waiters) =
|
||||
inspect_actor(&store, move |actor| {
|
||||
if poisoned {
|
||||
set_terminal(
|
||||
&actor.terminal_error,
|
||||
WalObjectSequenceExhaustedSnafu {
|
||||
last_object_seq: 1_u64,
|
||||
}
|
||||
.build(),
|
||||
);
|
||||
}
|
||||
let next_object_seq = actor.next_object_seq;
|
||||
actor.stopped.store(true, Ordering::Release);
|
||||
let result = actor.handle_handoff(one, id(9, 1));
|
||||
actor.stopped.store(false, Ordering::Release);
|
||||
(
|
||||
matches!(result, Err(Error::ObjectStoreWalStopped { .. })),
|
||||
actor.next_object_seq == next_object_seq,
|
||||
actor.pending_releases.len(),
|
||||
actor.handoff_waiters.len(),
|
||||
)
|
||||
})
|
||||
.await;
|
||||
assert!(stopped, "poisoned: {poisoned}");
|
||||
assert!(next_object_seq);
|
||||
assert_eq!(0, records);
|
||||
assert_eq!(0, waiters);
|
||||
let _ = store.stop().await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_store_handoff_starts_the_region_history_on_a_prefix_found_empty() {
|
||||
let _serialized = SERIALIZED.lock().await;
|
||||
let store = open(memory_store(), &config(MIN_FLUSH_INTERVAL, u64::MAX)).await;
|
||||
let (one, two) = (region(1), region(2));
|
||||
let bound = id(9, 1);
|
||||
store.handoff(&provider(one), bound).await.unwrap();
|
||||
|
||||
// The store accepts the history of the region handed over to it,
|
||||
// though it found its prefix empty, and only that one. The record
|
||||
// object reclaims the start object, and the store goes on taking
|
||||
// appends.
|
||||
assert_eq!(None, missing_history(&store, one, bound).await);
|
||||
assert!(missing_history(&store, two, 0).await.is_some());
|
||||
assert_eq!(vec![10], collected_object_seqs(&store).await);
|
||||
append(&store, two, "b1").await.unwrap();
|
||||
store.stop().await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_store_handoffs_in_one_interval_share_an_object() {
|
||||
let _serialized = SERIALIZED.lock().await;
|
||||
let store = open(memory_store(), &manual()).await;
|
||||
let (one, two) = (region(1), region(2));
|
||||
let handoffs = [one, two].map(|region_id| {
|
||||
let store = store.clone();
|
||||
tokio::spawn(async move { store.handoff(&provider(region_id), 0).await })
|
||||
});
|
||||
wait_for_handoff_waiters(&store, 2).await;
|
||||
assert!(handoffs.iter().all(|handoff| !handoff.is_finished()));
|
||||
|
||||
store.seal_open_batch().await.unwrap();
|
||||
for handoff in handoffs {
|
||||
handoff.await.unwrap().unwrap();
|
||||
}
|
||||
assert_eq!(vec![1], collected_object_seqs(&store).await);
|
||||
assert_eq!(
|
||||
vec![release(one, 0), release(two, 0)],
|
||||
releases_of(store.io.as_ref(), 1).await
|
||||
);
|
||||
store.stop().await.unwrap();
|
||||
}
|
||||
|
||||
/// A hand-off whose floor must pass ids in the open batch seals that batch
|
||||
/// first: an id of another region under the given bound, or an id issued
|
||||
/// to the region itself, whose largest issued id then is the bound. The
|
||||
/// record goes into the first object above the bound.
|
||||
#[tokio::test]
|
||||
async fn test_store_handoff_seals_the_open_batch_below_the_floor() {
|
||||
let _serialized = SERIALIZED.lock().await;
|
||||
let (one, two) = (region(1), region(2));
|
||||
// The appended region, the hand-off's entry id, the bound it returns
|
||||
// and the object of its record.
|
||||
for (appended_region, entry_id, bound, record_seq) in
|
||||
[(two, id(5, 1), id(5, 1), 6), (one, 0, id(1, 1), 2)]
|
||||
{
|
||||
let store = open(memory_store(), &manual()).await;
|
||||
// The append waits in the open batch under sequence 1.
|
||||
let [appended] = spawn_appends(&store, appended_region, 1)
|
||||
.await
|
||||
.try_into()
|
||||
.unwrap();
|
||||
let handoff = {
|
||||
let store = store.clone();
|
||||
tokio::spawn(async move { store.handoff(&provider(one), entry_id).await })
|
||||
};
|
||||
wait_for_handoff_waiters(&store, 1).await;
|
||||
// The hand-off's own seal created the object of the append.
|
||||
let appended = timeout(WAIT, appended).await.unwrap().unwrap().unwrap();
|
||||
assert_eq!(id(1, 1), appended.last_entry_ids[&appended_region]);
|
||||
store.seal_open_batch().await.unwrap();
|
||||
assert_eq!(
|
||||
bound,
|
||||
timeout(WAIT, handoff).await.unwrap().unwrap().unwrap()
|
||||
);
|
||||
assert_eq!(vec![1, record_seq], collected_object_seqs(&store).await);
|
||||
assert_eq!(
|
||||
vec![release(one, 0)],
|
||||
releases_of(store.io.as_ref(), record_seq).await
|
||||
);
|
||||
store.stop().await.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_store_handoff_without_io_permission_keeps_the_floor_and_the_record() {
|
||||
let _serialized = SERIALIZED.lock().await;
|
||||
let store = open(memory_store(), &manual()).await;
|
||||
let permit = Arc::new(TestIoPermit::default());
|
||||
store.set_io_permit(permit.clone()).unwrap();
|
||||
let one = region(1);
|
||||
let bound = id(5, 1);
|
||||
let error = store.handoff(&provider(one), bound).await.unwrap_err();
|
||||
assert!(
|
||||
matches!(error, Error::ObjectStoreWalLeaseExpired { .. }),
|
||||
"unexpected error: {error:?}"
|
||||
);
|
||||
assert!(error.retry_hint().is_retryable());
|
||||
|
||||
// Once permission returns, the record goes into an object above the
|
||||
// bound, and later ids of the region are above it too.
|
||||
permit.0.store(true, Ordering::Release);
|
||||
store.seal_open_batch().await.unwrap();
|
||||
assert_eq!(
|
||||
vec![release(one, 0)],
|
||||
releases_of(store.io.as_ref(), 6).await
|
||||
);
|
||||
let [append_one] = spawn_appends(&store, one, 1).await.try_into().unwrap();
|
||||
store.seal_open_batch().await.unwrap();
|
||||
let next = timeout(WAIT, append_one)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.last_entry_ids[&one];
|
||||
assert!(next > bound, "{next} is not above {bound}");
|
||||
store.stop().await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_store_enqueued_handoff_behind_an_open_batch_without_io_permission_keeps_the_floor()
|
||||
{
|
||||
let _serialized = SERIALIZED.lock().await;
|
||||
let store = open(memory_store(), &enqueued(manual())).await;
|
||||
let permit = Arc::new(TestIoPermit(AtomicBool::new(true)));
|
||||
store.set_io_permit(permit.clone()).unwrap();
|
||||
let (one, two) = (region(1), region(2));
|
||||
// Acknowledged on admission, the entry stays in the open batch under
|
||||
// sequence 1.
|
||||
let appended = append(&store, two, "b1").await.unwrap().last_entry_ids[&two];
|
||||
assert_eq!(id(1, 1), appended);
|
||||
permit.0.store(false, Ordering::Release);
|
||||
let bound = id(5, 1);
|
||||
let error = store.handoff(&provider(one), bound).await.unwrap_err();
|
||||
assert!(
|
||||
matches!(error, Error::ObjectStoreWalLeaseExpired { .. }),
|
||||
"unexpected error: {error:?}"
|
||||
);
|
||||
assert!(error.retry_hint().is_retryable());
|
||||
// Retries keep one deferred bound per region, the largest.
|
||||
let largest = id(9, 1);
|
||||
for retry in [bound, largest, bound] {
|
||||
assert!(store.handoff(&provider(one), retry).await.is_err());
|
||||
}
|
||||
assert_eq!(
|
||||
vec![(one, largest)],
|
||||
inspect_actor(&store, |actor| actor
|
||||
.deferred_handoffs
|
||||
.iter()
|
||||
.map(|(region_id, bound)| (*region_id, *bound))
|
||||
.collect::<Vec<_>>())
|
||||
.await
|
||||
);
|
||||
let bound = largest;
|
||||
|
||||
// Once permission returns, the open batch is sealed under its own
|
||||
// sequence and the record goes into the first object above the
|
||||
// bound, without another hand-off.
|
||||
permit.0.store(true, Ordering::Release);
|
||||
store.seal_open_batch().await.unwrap();
|
||||
store.seal_open_batch().await.unwrap();
|
||||
assert_eq!(
|
||||
vec![release(one, 0)],
|
||||
releases_of(store.io.as_ref(), 10).await
|
||||
);
|
||||
assert_eq!(
|
||||
expected_entries(two, &[(appended, "b1")]),
|
||||
read_entries(&store, two, 0).await
|
||||
);
|
||||
let next = append(&store, one, "a1").await.unwrap().last_entry_ids[&one];
|
||||
assert!(next > bound, "{next} is not above {bound}");
|
||||
store.stop().await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_store_cancelled_handoffs_leave_at_most_one_closed_waiter() {
|
||||
let _serialized = SERIALIZED.lock().await;
|
||||
let store = open(memory_store(), &manual()).await;
|
||||
let one = region(1);
|
||||
// Each caller stops waiting before the record's object is sealed; each
|
||||
// admission drops the closed waiters before it, so only the last one
|
||||
// is left.
|
||||
let (waiters, records) = inspect_actor(&store, move |actor| {
|
||||
for _ in 0..3 {
|
||||
drop(actor.handle_handoff(one, id(5, 1)).unwrap());
|
||||
}
|
||||
(actor.handoff_waiters.len(), actor.pending_releases.len())
|
||||
})
|
||||
.await;
|
||||
assert_eq!((1, 1), (waiters, records));
|
||||
store.stop().await.unwrap();
|
||||
}
|
||||
|
||||
/// A durable hand-off whose record was not yet sealed into a batch when
|
||||
/// stop begins is sealed into stop's last object and gets that object's
|
||||
/// outcome: success with its record, or stopped if the create fails.
|
||||
#[tokio::test]
|
||||
async fn test_store_pending_handoff_at_stop_gets_the_last_object() {
|
||||
let _serialized = SERIALIZED.lock().await;
|
||||
for fail in [false, true] {
|
||||
let store = open(memory_store(), &manual()).await;
|
||||
let one = region(1);
|
||||
let handoff = {
|
||||
let store = store.clone();
|
||||
tokio::spawn(async move { store.handoff(&provider(one), 0).await })
|
||||
};
|
||||
wait_for_handoff_waiters(&store, 1).await;
|
||||
store.hold_creates();
|
||||
let stop = {
|
||||
let store = store.clone();
|
||||
tokio::spawn(async move { store.stop().await })
|
||||
};
|
||||
store.wait_for_parked_creates(1).await.unwrap();
|
||||
assert!(!handoff.is_finished());
|
||||
if fail {
|
||||
store.fail_creates();
|
||||
}
|
||||
store.release_creates();
|
||||
let handoff = timeout(WAIT, handoff).await.unwrap().unwrap();
|
||||
let stopped = timeout(WAIT, stop).await.unwrap().unwrap();
|
||||
if fail {
|
||||
assert!(
|
||||
matches!(handoff, Err(Error::ObjectStoreWalStopped { .. })),
|
||||
"{handoff:?}"
|
||||
);
|
||||
// Stop reports the record it lost.
|
||||
assert!(stopped.is_err());
|
||||
} else {
|
||||
handoff.unwrap();
|
||||
stopped.unwrap();
|
||||
assert_eq!(
|
||||
vec![release(one, 0)],
|
||||
releases_of(store.io.as_ref(), 1).await
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_store_deferred_handoff_sealed_after_stop_began_keeps_no_record() {
|
||||
let _serialized = SERIALIZED.lock().await;
|
||||
let store = open(memory_store(), &enqueued(manual())).await;
|
||||
let permit = Arc::new(TestIoPermit(AtomicBool::new(true)));
|
||||
store.set_io_permit(permit.clone()).unwrap();
|
||||
let (one, two) = (region(1), region(2));
|
||||
append(&store, two, "b1").await.unwrap();
|
||||
permit.0.store(false, Ordering::Release);
|
||||
assert!(store.handoff(&provider(one), id(5, 1)).await.is_err());
|
||||
permit.0.store(true, Ordering::Release);
|
||||
// A seal after stop began moves no deferred floor, so it keeps no record.
|
||||
let records = inspect_actor(&store, |actor| {
|
||||
actor.stopped.store(true, Ordering::Release);
|
||||
actor.flush_open_batch();
|
||||
actor.stopped.store(false, Ordering::Release);
|
||||
actor.pending_releases.len()
|
||||
})
|
||||
.await;
|
||||
assert_eq!(0, records);
|
||||
store.stop().await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_store_durable_handoff_behind_an_open_batch_without_io_permission_keeps_the_floor()
|
||||
{
|
||||
let _serialized = SERIALIZED.lock().await;
|
||||
let store = open(memory_store(), &manual()).await;
|
||||
let permit = Arc::new(TestIoPermit(AtomicBool::new(true)));
|
||||
store.set_io_permit(permit.clone()).unwrap();
|
||||
let (one, two) = (region(1), region(2));
|
||||
// The append waits in the open batch under sequence 1.
|
||||
let appended = spawn_appends(&store, two, 1).await.pop().unwrap();
|
||||
permit.0.store(false, Ordering::Release);
|
||||
let bound = id(5, 1);
|
||||
let error = store.handoff(&provider(one), bound).await.unwrap_err();
|
||||
assert!(
|
||||
matches!(error, Error::ObjectStoreWalLeaseExpired { .. }),
|
||||
"unexpected error: {error:?}"
|
||||
);
|
||||
assert!(error.retry_hint().is_retryable());
|
||||
// Losing permission rolled the open batch back.
|
||||
assert!(timeout(WAIT, appended).await.unwrap().unwrap().is_err());
|
||||
|
||||
// Once permission returns, the record goes into the first object
|
||||
// above the bound without another hand-off or append.
|
||||
permit.0.store(true, Ordering::Release);
|
||||
store.seal_open_batch().await.unwrap();
|
||||
assert_eq!(
|
||||
vec![release(one, 0)],
|
||||
releases_of(store.io.as_ref(), 6).await
|
||||
);
|
||||
let next = spawn_appends(&store, one, 1).await.pop().unwrap();
|
||||
store.seal_open_batch().await.unwrap();
|
||||
let next = timeout(WAIT, next)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.last_entry_ids[&one];
|
||||
assert!(next > bound, "{next} is not above {bound}");
|
||||
store.stop().await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_store_handoff_fails_while_the_store_is_failing_and_keeps_the_floor() {
|
||||
let _serialized = SERIALIZED.lock().await;
|
||||
let (store, io, mut parked) =
|
||||
open_parking_creates(memory_store(), &enqueued(manual())).await;
|
||||
let (one, two, three) = (region(1), region(2), region(3));
|
||||
let appended = append(&store, two, "b1").await.unwrap().last_entry_ids[&two];
|
||||
let sealed = {
|
||||
let store = store.clone();
|
||||
tokio::spawn(async move { store.seal_open_batch().await })
|
||||
};
|
||||
let (object_seq, create) = next_parked_operation(&mut parked).await;
|
||||
assert_eq!(1, object_seq);
|
||||
let (one_bound, three_bound) = (id(5, 1), id(7, 1));
|
||||
let waiting = {
|
||||
let store = store.clone();
|
||||
tokio::spawn(async move { store.handoff(&provider(one), one_bound).await })
|
||||
};
|
||||
wait_for_handoff_waiters(&store, 1).await;
|
||||
|
||||
// The refused create makes the store fail: the waiting hand-off and
|
||||
// one admitted afterwards fail at once.
|
||||
io.creates_refused.store(true, Ordering::SeqCst);
|
||||
create.send(false).unwrap();
|
||||
let error = timeout(WAIT, waiting).await.unwrap().unwrap().unwrap_err();
|
||||
assert_rejected(&error, ErrorKind::PermissionDenied);
|
||||
let error = store
|
||||
.handoff(&provider(three), three_bound)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_rejected(&error, ErrorKind::PermissionDenied);
|
||||
|
||||
// Once a create succeeds, both records go into the first object above
|
||||
// both bounds without another hand-off, and later ids are above them.
|
||||
io.creates_refused.store(false, Ordering::SeqCst);
|
||||
let (object_seq, create) = next_parked_operation(&mut parked).await;
|
||||
assert_eq!(1, object_seq);
|
||||
create.send(true).unwrap();
|
||||
timeout(WAIT, sealed).await.unwrap().unwrap().unwrap();
|
||||
assert_eq!(0, failing_stores());
|
||||
assert_eq!(
|
||||
expected_entries(two, &[(appended, "b1")]),
|
||||
read_entries(&store, two, 0).await
|
||||
);
|
||||
let sealed = {
|
||||
let store = store.clone();
|
||||
tokio::spawn(async move { store.seal_open_batch().await })
|
||||
};
|
||||
let (object_seq, create) = next_parked_operation(&mut parked).await;
|
||||
assert_eq!(8, object_seq);
|
||||
create.send(true).unwrap();
|
||||
timeout(WAIT, sealed).await.unwrap().unwrap().unwrap();
|
||||
assert_eq!(
|
||||
vec![release(one, 0), release(three, 0)],
|
||||
releases_of(io.as_ref(), 8).await
|
||||
);
|
||||
io.creates_parked.store(false, Ordering::SeqCst);
|
||||
let next = append(&store, one, "a1").await.unwrap().last_entry_ids[&one];
|
||||
assert!(next > three_bound, "{next} is not above {three_bound}");
|
||||
store.stop().await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_store_handoff_waiting_for_its_object_fails_when_io_permission_is_lost() {
|
||||
let _serialized = SERIALIZED.lock().await;
|
||||
let store = open(memory_store(), &manual()).await;
|
||||
let permit = Arc::new(TestIoPermit(AtomicBool::new(true)));
|
||||
store.set_io_permit(permit.clone()).unwrap();
|
||||
let one = region(1);
|
||||
let bound = id(5, 1);
|
||||
let handoff = {
|
||||
let store = store.clone();
|
||||
tokio::spawn(async move { store.handoff(&provider(one), bound).await })
|
||||
};
|
||||
wait_for_handoff_waiters(&store, 1).await;
|
||||
|
||||
// The hand-off fails as soon as the store loses permission, and its
|
||||
// record goes above the bound once permission returns.
|
||||
permit.0.store(false, Ordering::Release);
|
||||
assert!(store.seal_open_batch().await.is_err());
|
||||
let error = timeout(WAIT, handoff).await.unwrap().unwrap().unwrap_err();
|
||||
assert!(error.retry_hint().is_retryable(), "{error:?}");
|
||||
assert!(
|
||||
format!("{error:?}").contains("node lease is unavailable or expired"),
|
||||
"unexpected error: {error:?}"
|
||||
);
|
||||
permit.0.store(true, Ordering::Release);
|
||||
store.seal_open_batch().await.unwrap();
|
||||
assert_eq!(
|
||||
vec![release(one, 0)],
|
||||
releases_of(store.io.as_ref(), 6).await
|
||||
);
|
||||
store.stop().await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_store_enqueued_handoff_answers_once_its_object_is_durable() {
|
||||
let _serialized = SERIALIZED.lock().await;
|
||||
let store = open(memory_store(), &enqueued(manual())).await;
|
||||
let one = region(1);
|
||||
store.hold_creates();
|
||||
let handoff = {
|
||||
let store = store.clone();
|
||||
tokio::spawn(async move { store.handoff(&provider(one), 0).await })
|
||||
};
|
||||
wait_for_handoff_waiters(&store, 1).await;
|
||||
let seal = {
|
||||
let store = store.clone();
|
||||
tokio::spawn(async move { store.seal_open_batch().await })
|
||||
};
|
||||
store.wait_for_parked_creates(1).await.unwrap();
|
||||
assert!(!handoff.is_finished());
|
||||
|
||||
store.release_creates();
|
||||
timeout(WAIT, seal).await.unwrap().unwrap().unwrap();
|
||||
timeout(WAIT, handoff).await.unwrap().unwrap().unwrap();
|
||||
store.stop().await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_store_recovery_seeds_watermarks_from_release_records() {
|
||||
let _serialized = SERIALIZED.lock().await;
|
||||
|
||||
@@ -23,7 +23,9 @@ use common_config::KvBackendConfig;
|
||||
use common_error::ext::BoxedError;
|
||||
use common_meta::error as meta_error;
|
||||
use common_meta::kv_backend::txn::{Txn, TxnOp, TxnOpResponse, TxnRequest, TxnResponse};
|
||||
use common_meta::kv_backend::{ClosableKvBackend, KvBackend, TxnService};
|
||||
use common_meta::kv_backend::{
|
||||
ClosableKvBackend, KvBackend, KvBackendCapabilities, TxnCapability, TxnService,
|
||||
};
|
||||
use common_meta::rpc::KeyValue;
|
||||
use common_meta::rpc::store::{
|
||||
BatchDeleteRequest, BatchDeleteResponse, BatchGetRequest, BatchGetResponse, BatchPutRequest,
|
||||
@@ -208,13 +210,21 @@ impl TxnService for RaftEngineBackend {
|
||||
})
|
||||
}
|
||||
|
||||
fn max_txn_ops(&self) -> usize {
|
||||
usize::MAX
|
||||
fn txn_capability(&self) -> Option<TxnCapability> {
|
||||
Some(TxnCapability {
|
||||
max_ops: usize::MAX,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl KvBackend for RaftEngineBackend {
|
||||
fn capabilities(&self) -> KvBackendCapabilities {
|
||||
KvBackendCapabilities {
|
||||
atomic_batch_put: true,
|
||||
}
|
||||
}
|
||||
|
||||
fn name(&self) -> &str {
|
||||
"RaftEngineBackend"
|
||||
}
|
||||
@@ -478,6 +488,15 @@ mod tests {
|
||||
RaftEngineBackend::try_open_with_cfg(dir, &KvBackendConfig::default()).unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_atomic_checkpoint_round_trip() {
|
||||
let dir = create_temp_dir("raft-atomic-checkpoint");
|
||||
common_meta::kv_backend::test::check_atomic_checkpoint_round_trip(Arc::new(
|
||||
build_kv_backend(dir.path().to_str().unwrap().to_string()),
|
||||
))
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_close_closes_active_log_file() {
|
||||
let dir = create_temp_dir("raft-engine-kv-close-test");
|
||||
|
||||
@@ -13,16 +13,18 @@
|
||||
// limitations under the License.
|
||||
|
||||
use std::any::Any;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use api::v1::meta::MailboxMessage;
|
||||
use common_meta::instruction::{Instruction, InstructionReply, SyncRegionReply, SyncRegionsReply};
|
||||
use common_meta::instruction::{
|
||||
Instruction, InstructionReply, MetadataCompaction, SyncRegionReply, SyncRegionsReply,
|
||||
};
|
||||
use common_meta::peer::Peer;
|
||||
use common_meta::rpc::router::RegionRoute;
|
||||
use common_procedure::{Context as ProcedureContext, Status};
|
||||
use common_telemetry::info;
|
||||
use common_telemetry::tracing_context::TracingContext;
|
||||
use common_telemetry::{info, warn};
|
||||
use futures::future::join_all;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use snafu::{OptionExt, ResultExt, ensure};
|
||||
@@ -57,7 +59,7 @@ impl State for SyncRegion {
|
||||
_procedure_ctx: &ProcedureContext,
|
||||
) -> Result<(Box<dyn State>, Status)> {
|
||||
Self::flush_central_region(ctx).await?;
|
||||
self.sync_regions(ctx).await?;
|
||||
self.sync_with_paused_source(ctx).await?;
|
||||
|
||||
Ok((
|
||||
Box::new(UpdateMetadata::ApplyStaging),
|
||||
@@ -91,6 +93,75 @@ impl SyncRegion {
|
||||
.await
|
||||
}
|
||||
|
||||
async fn sync_with_paused_source(&self, ctx: &mut Context) -> Result<()> {
|
||||
let prepare = ctx.persistent_ctx.group_prepare_result.as_ref().unwrap();
|
||||
let source = prepare.central_region_datanode.clone();
|
||||
let region_id = prepare.central_region;
|
||||
let remaining = ctx
|
||||
.next_operation_timeout()
|
||||
.context(error::ExceededDeadlineSnafu {
|
||||
operation: "Pause source metadata compaction",
|
||||
})?;
|
||||
let pause = Instruction::MetadataCompaction(MetadataCompaction::Pause {
|
||||
region_id,
|
||||
remaining,
|
||||
});
|
||||
let reply =
|
||||
Self::request(&ctx.mailbox, &ctx.server_addr, &source, pause, remaining).await?;
|
||||
let InstructionReply::MetadataCompaction(reply) = reply else {
|
||||
return error::UnexpectedInstructionReplySnafu {
|
||||
mailbox_message: reply.to_string(),
|
||||
reason: "expected source metadata compaction pause acknowledgement",
|
||||
}
|
||||
.fail();
|
||||
};
|
||||
if let Some(err) = reply.error {
|
||||
return instruction_error_result(
|
||||
&err,
|
||||
format!(
|
||||
"Failed to pause compaction for {}: {}",
|
||||
region_id, err.message
|
||||
),
|
||||
);
|
||||
}
|
||||
ensure!(
|
||||
reply.result,
|
||||
error::RetryLaterSnafu {
|
||||
reason: format!(
|
||||
"Source {} did not confirm metadata compaction pause",
|
||||
region_id
|
||||
)
|
||||
}
|
||||
);
|
||||
|
||||
// A lost reply may leave a target copying. The source releases its guard
|
||||
// at the deadline if we cannot confirm that every target finished.
|
||||
let mut all_replied = true;
|
||||
let result = self.sync_regions(ctx, &mut all_replied).await;
|
||||
if all_replied {
|
||||
let release =
|
||||
Instruction::MetadataCompaction(MetadataCompaction::Release { region_id });
|
||||
if let Err(err) = Self::release_source(ctx, &source, release).await {
|
||||
warn!(err; "Failed to release source metadata compaction for {region_id}");
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
async fn release_source(ctx: &Context, source: &Peer, release: Instruction) -> Result<()> {
|
||||
let msg = Self::message(&ctx.server_addr, source, &release)?;
|
||||
let channel = Channel::Datanode(source.id);
|
||||
tokio::time::timeout(
|
||||
ctx.next_operation_timeout().unwrap_or_default(),
|
||||
ctx.mailbox.send_oneway(&channel, msg),
|
||||
)
|
||||
.await
|
||||
.ok()
|
||||
.context(error::ExceededDeadlineSnafu {
|
||||
operation: "Release source metadata compaction",
|
||||
})?
|
||||
}
|
||||
|
||||
/// Builds instructions to sync regions on datanodes.
|
||||
fn build_sync_region_instructions(
|
||||
central_region: RegionId,
|
||||
@@ -117,7 +188,7 @@ impl SyncRegion {
|
||||
}
|
||||
|
||||
/// Syncs regions on datanodes.
|
||||
async fn sync_regions(&self, ctx: &mut Context) -> Result<()> {
|
||||
async fn sync_regions(&self, ctx: &mut Context, all_replied: &mut bool) -> Result<()> {
|
||||
let table_id = ctx.persistent_ctx.table_id;
|
||||
let prepare_result = ctx.persistent_ctx.group_prepare_result.as_ref().unwrap();
|
||||
let instructions = Self::build_sync_region_instructions(
|
||||
@@ -135,11 +206,11 @@ impl SyncRegion {
|
||||
.map(|(peer, sync_regions)| {
|
||||
(
|
||||
peer,
|
||||
Self::sync_region(
|
||||
Self::request(
|
||||
&ctx.mailbox,
|
||||
&ctx.server_addr,
|
||||
peer,
|
||||
sync_regions,
|
||||
Instruction::SyncRegions(sync_regions.clone()),
|
||||
operation_timeout,
|
||||
),
|
||||
)
|
||||
@@ -159,7 +230,33 @@ impl SyncRegion {
|
||||
)
|
||||
};
|
||||
|
||||
let results = join_all(tasks).await;
|
||||
let now = Instant::now();
|
||||
let replies = join_all(tasks).await;
|
||||
let results = replies
|
||||
.into_iter()
|
||||
.zip(&peers)
|
||||
.map(|(reply, peer)| match reply {
|
||||
Ok(InstructionReply::SyncRegions(SyncRegionsReply { replies }))
|
||||
if Self::received_all(&instructions[*peer], &replies) =>
|
||||
{
|
||||
replies
|
||||
.iter()
|
||||
.try_for_each(|reply| Self::handle_sync_region_reply(reply, &now, peer))
|
||||
}
|
||||
Ok(reply) => {
|
||||
*all_replied = false;
|
||||
error::UnexpectedInstructionReplySnafu {
|
||||
mailbox_message: reply.to_string(),
|
||||
reason: "expected replies from all requested sync regions",
|
||||
}
|
||||
.fail()
|
||||
}
|
||||
Err(err) => {
|
||||
*all_replied = false;
|
||||
Err(err)
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let result = handle_multiple_results(&results);
|
||||
|
||||
match result {
|
||||
@@ -211,32 +308,33 @@ impl SyncRegion {
|
||||
}
|
||||
}
|
||||
|
||||
/// Syncs regions on a datanode.
|
||||
async fn sync_region(
|
||||
mailbox: &MailboxRef,
|
||||
fn message(
|
||||
server_addr: &str,
|
||||
peer: &Peer,
|
||||
sync_regions: &[common_meta::instruction::SyncRegion],
|
||||
timeout: Duration,
|
||||
) -> Result<()> {
|
||||
let ch = Channel::Datanode(peer.id);
|
||||
let instruction = Instruction::SyncRegions(sync_regions.to_vec());
|
||||
let tracing_ctx = TracingContext::from_current_span();
|
||||
let message = MailboxMessage::json_message(
|
||||
&format!(
|
||||
"Sync regions: {:?}",
|
||||
sync_regions.iter().map(|r| r.region_id).collect::<Vec<_>>()
|
||||
),
|
||||
&format!("Metasrv@{}", server_addr),
|
||||
instruction: &Instruction,
|
||||
) -> Result<MailboxMessage> {
|
||||
MailboxMessage::json_message(
|
||||
&instruction.to_string(),
|
||||
&format!("Metasrv@{server_addr}"),
|
||||
&format!("Datanode-{}@{}", peer.id, peer.addr),
|
||||
common_time::util::current_time_millis(),
|
||||
&instruction,
|
||||
Some(tracing_ctx.to_w3c()),
|
||||
instruction,
|
||||
Some(TracingContext::from_current_span().to_w3c()),
|
||||
)
|
||||
.with_context(|_| error::SerializeToJsonSnafu {
|
||||
input: instruction.to_string(),
|
||||
})?;
|
||||
})
|
||||
}
|
||||
|
||||
async fn request(
|
||||
mailbox: &MailboxRef,
|
||||
server_addr: &str,
|
||||
peer: &Peer,
|
||||
instruction: Instruction,
|
||||
timeout: Duration,
|
||||
) -> Result<InstructionReply> {
|
||||
let ch = Channel::Datanode(peer.id);
|
||||
let message = Self::message(server_addr, peer, &instruction)?;
|
||||
let now = std::time::Instant::now();
|
||||
let receiver = mailbox.send(&ch, message, timeout).await;
|
||||
|
||||
@@ -256,25 +354,7 @@ impl SyncRegion {
|
||||
};
|
||||
|
||||
match receiver.await {
|
||||
Ok(msg) => {
|
||||
let reply = HeartbeatMailbox::json_reply(&msg)?;
|
||||
info!(
|
||||
"Received sync regions reply: {:?}, elapsed: {:?}",
|
||||
reply,
|
||||
now.elapsed()
|
||||
);
|
||||
let InstructionReply::SyncRegions(SyncRegionsReply { replies }) = reply else {
|
||||
return error::UnexpectedInstructionReplySnafu {
|
||||
mailbox_message: msg.to_string(),
|
||||
reason: "expect sync regions reply",
|
||||
}
|
||||
.fail();
|
||||
};
|
||||
for reply in replies {
|
||||
Self::handle_sync_region_reply(&reply, &now, peer)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Ok(msg) => HeartbeatMailbox::json_reply(&msg),
|
||||
Err(error::Error::MailboxChannelClosed { .. }) => error::RetryLaterSnafu {
|
||||
reason: format!(
|
||||
"Mailbox closed when sending sync region to datanode {:?}, elapsed: {:?}",
|
||||
@@ -295,6 +375,19 @@ impl SyncRegion {
|
||||
}
|
||||
}
|
||||
|
||||
fn received_all(
|
||||
requests: &[common_meta::instruction::SyncRegion],
|
||||
replies: &[SyncRegionReply],
|
||||
) -> bool {
|
||||
if requests.len() != replies.len() {
|
||||
return false;
|
||||
}
|
||||
let ids: HashSet<_> = replies.iter().map(|reply| reply.region_id).collect();
|
||||
requests
|
||||
.iter()
|
||||
.all(|request| ids.contains(&request.region_id))
|
||||
}
|
||||
|
||||
fn handle_sync_region_reply(
|
||||
SyncRegionReply {
|
||||
region_id,
|
||||
@@ -404,6 +497,123 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_source_pause_release_follows_target_reply() {
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::handler::HeartbeatMailbox;
|
||||
use common_meta::instruction::{
|
||||
Instruction, InstructionReply, MetadataCompaction, SimpleReply,
|
||||
};
|
||||
|
||||
for outcome in ["success", "region_error", "lost_reply", "pause_rejected"] {
|
||||
let mut env = TestingEnv::new();
|
||||
let mut persistent = new_persistent_context(1024, vec![], vec![]);
|
||||
persistent.group_prepare_result = Some(test_prepare_result(1024));
|
||||
let budget = persistent.timeout;
|
||||
let (source_tx, mut source_rx) = tokio::sync::mpsc::channel(2);
|
||||
let (target_tx, mut target_rx) = tokio::sync::mpsc::channel(1);
|
||||
env.mailbox_ctx
|
||||
.insert_heartbeat_response_receiver(Channel::Datanode(1), source_tx)
|
||||
.await;
|
||||
env.mailbox_ctx
|
||||
.insert_heartbeat_response_receiver(Channel::Datanode(2), target_tx)
|
||||
.await;
|
||||
let mut ctx = env.create_context(persistent);
|
||||
let mailbox = ctx.mailbox.clone();
|
||||
let target = RegionId::new(1024, 3);
|
||||
let sync = SyncRegion {
|
||||
region_routes: vec![RegionRoute {
|
||||
region: Region {
|
||||
id: target,
|
||||
..Default::default()
|
||||
},
|
||||
leader_peer: Some(Peer::empty(2)),
|
||||
..Default::default()
|
||||
}],
|
||||
};
|
||||
let peers = async {
|
||||
let msg = source_rx
|
||||
.recv()
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.mailbox_message
|
||||
.unwrap();
|
||||
let Instruction::MetadataCompaction(MetadataCompaction::Pause {
|
||||
region_id,
|
||||
remaining,
|
||||
}) = HeartbeatMailbox::json_instruction(&msg).unwrap()
|
||||
else {
|
||||
panic!("expected pause")
|
||||
};
|
||||
assert_eq!(region_id, RegionId::new(1024, 1));
|
||||
assert!(remaining > Duration::ZERO && remaining <= budget);
|
||||
assert!(target_rx.try_recv().is_err());
|
||||
let mut ack = msg.clone();
|
||||
ack.payload = Some(api::v1::meta::mailbox_message::Payload::Json(
|
||||
serde_json::to_string(&InstructionReply::MetadataCompaction(SimpleReply {
|
||||
result: outcome != "pause_rejected",
|
||||
error: None,
|
||||
}))
|
||||
.unwrap(),
|
||||
));
|
||||
mailbox.on_recv(msg.id, Ok(ack)).await.unwrap();
|
||||
if outcome == "pause_rejected" {
|
||||
return region_id;
|
||||
}
|
||||
let msg = target_rx
|
||||
.recv()
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.mailbox_message
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
HeartbeatMailbox::json_instruction(&msg).unwrap(),
|
||||
Instruction::SyncRegions(_)
|
||||
));
|
||||
assert!(source_rx.try_recv().is_err());
|
||||
let reply = match outcome {
|
||||
"lost_reply" => crate::error::MailboxTimeoutSnafu { id: msg.id }.fail(),
|
||||
"region_error" => Ok(new_sync_region_reply(
|
||||
msg.id,
|
||||
target,
|
||||
false,
|
||||
true,
|
||||
Some("sync failed".into()),
|
||||
)),
|
||||
_ => Ok(new_sync_region_reply(msg.id, target, true, true, None)),
|
||||
};
|
||||
mailbox.on_recv(msg.id, reply).await.unwrap();
|
||||
region_id
|
||||
};
|
||||
let (region_id, result) = tokio::time::timeout(Duration::from_secs(5), async {
|
||||
tokio::join!(peers, sync.sync_with_paused_source(&mut ctx))
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(result.is_ok(), outcome == "success");
|
||||
if outcome == "pause_rejected" {
|
||||
assert!(target_rx.try_recv().is_err());
|
||||
}
|
||||
if matches!(outcome, "lost_reply" | "pause_rejected") {
|
||||
assert!(source_rx.try_recv().is_err());
|
||||
} else {
|
||||
let msg = source_rx
|
||||
.try_recv()
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.mailbox_message
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
HeartbeatMailbox::json_instruction(&msg).unwrap(),
|
||||
Instruction::MetadataCompaction(MetadataCompaction::Release { region_id })
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_sync_regions_all_successful() {
|
||||
let mut env = TestingEnv::new();
|
||||
@@ -436,7 +646,7 @@ mod tests {
|
||||
}];
|
||||
let sync_region = SyncRegion { region_routes };
|
||||
|
||||
sync_region.sync_regions(&mut ctx).await.unwrap();
|
||||
sync_region.sync_regions(&mut ctx, &mut true).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -457,49 +667,117 @@ mod tests {
|
||||
}];
|
||||
let sync_region = SyncRegion { region_routes };
|
||||
|
||||
let err = sync_region.sync_regions(&mut ctx).await.unwrap_err();
|
||||
let err = sync_region
|
||||
.sync_regions(&mut ctx, &mut true)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_matches!(err, Error::RetryLater { .. });
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_sync_regions_retryable_instruction_error() {
|
||||
let mut env = TestingEnv::new();
|
||||
let table_id = 1024;
|
||||
let region_id = RegionId::new(table_id, 3);
|
||||
let mut persistent_context = new_persistent_context(table_id, vec![], vec![]);
|
||||
persistent_context.group_prepare_result = Some(test_prepare_result(table_id));
|
||||
async fn test_procedure_reissues_sync_after_retryable_copy_error() {
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
let (tx, rx) = tokio::sync::mpsc::channel(1);
|
||||
use common_meta::instruction::{
|
||||
Instruction, InstructionReply, MetadataCompaction, SimpleReply,
|
||||
};
|
||||
use common_meta::state_store::KvStateStore;
|
||||
use common_procedure::local::{LocalManager, ManagerConfig};
|
||||
use common_procedure::{ProcedureManager, ProcedureWithId};
|
||||
|
||||
use crate::handler::HeartbeatMailbox;
|
||||
use crate::procedure::repartition::group::RepartitionGroupProcedure;
|
||||
use crate::procedure::test_util::new_flush_region_reply_for_region;
|
||||
|
||||
let mut env = TestingEnv::new();
|
||||
let (tx, mut rx) = tokio::sync::mpsc::channel(8);
|
||||
env.mailbox_ctx
|
||||
.insert_heartbeat_response_receiver(Channel::Datanode(1), tx)
|
||||
.await;
|
||||
send_mock_reply(env.mailbox_ctx.mailbox().clone(), rx, move |id| {
|
||||
Ok(new_sync_region_reply_with_error(
|
||||
id,
|
||||
region_id,
|
||||
false,
|
||||
true,
|
||||
Some(InstructionError {
|
||||
code: StatusCode::StorageUnavailable,
|
||||
message: "manifest delta disappeared".to_string(),
|
||||
retry_hint: RetryHint::Retryable,
|
||||
}),
|
||||
))
|
||||
});
|
||||
|
||||
let mut ctx = env.create_context(persistent_context);
|
||||
let sync_region = SyncRegion {
|
||||
region_routes: vec![RegionRoute {
|
||||
region: Region {
|
||||
id: region_id,
|
||||
let mut persistent = new_persistent_context(1024, vec![], vec![]);
|
||||
let source = RegionId::new(1024, 1);
|
||||
let target = RegionId::new(1024, 3);
|
||||
persistent.group_prepare_result = Some(test_prepare_result(1024));
|
||||
let procedure = RepartitionGroupProcedure {
|
||||
context: env.create_context(persistent),
|
||||
state: Box::new(SyncRegion {
|
||||
region_routes: vec![RegionRoute {
|
||||
region: Region {
|
||||
id: target,
|
||||
..Default::default()
|
||||
},
|
||||
leader_peer: Some(Peer::empty(1)),
|
||||
..Default::default()
|
||||
},
|
||||
leader_peer: Some(Peer::empty(1)),
|
||||
..Default::default()
|
||||
}],
|
||||
}],
|
||||
}),
|
||||
};
|
||||
|
||||
let err = sync_region.sync_regions(&mut ctx).await.unwrap_err();
|
||||
assert_matches!(err, Error::RetryLater { .. });
|
||||
let store = Arc::new(KvStateStore::new(env.kv_backend.clone()));
|
||||
let manager = LocalManager::new(
|
||||
ManagerConfig {
|
||||
retry_delay: Duration::from_millis(1),
|
||||
..Default::default()
|
||||
},
|
||||
store.clone(),
|
||||
store,
|
||||
None,
|
||||
None,
|
||||
);
|
||||
manager.start().await.unwrap();
|
||||
let _watcher = manager
|
||||
.submit(ProcedureWithId::with_random_id(Box::new(procedure)))
|
||||
.await
|
||||
.unwrap();
|
||||
let mailbox = env.mailbox_ctx.mailbox();
|
||||
let mut first_sync_id = None;
|
||||
tokio::time::timeout(Duration::from_secs(10), async {
|
||||
loop {
|
||||
let mut msg = rx.recv().await.unwrap().unwrap().mailbox_message.unwrap();
|
||||
let id = msg.id;
|
||||
let reply = match HeartbeatMailbox::json_instruction(&msg).unwrap() {
|
||||
Instruction::FlushRegions(_) => {
|
||||
new_flush_region_reply_for_region(id, source, true, None)
|
||||
}
|
||||
Instruction::MetadataCompaction(MetadataCompaction::Pause { .. }) => {
|
||||
msg.payload = Some(api::v1::meta::mailbox_message::Payload::Json(
|
||||
serde_json::to_string(&InstructionReply::MetadataCompaction(
|
||||
SimpleReply {
|
||||
result: true,
|
||||
error: None,
|
||||
},
|
||||
))
|
||||
.unwrap(),
|
||||
));
|
||||
msg
|
||||
}
|
||||
Instruction::MetadataCompaction(MetadataCompaction::Release { .. }) => continue,
|
||||
Instruction::SyncRegions(requests) => {
|
||||
assert_eq!(requests.len(), 1);
|
||||
assert_eq!(requests[0].region_id, target);
|
||||
if let Some(first) = first_sync_id {
|
||||
assert_ne!(id, first);
|
||||
break;
|
||||
}
|
||||
first_sync_id = Some(id);
|
||||
new_sync_region_reply_with_error(
|
||||
id,
|
||||
target,
|
||||
false,
|
||||
true,
|
||||
Some(InstructionError::new(
|
||||
StatusCode::StorageUnavailable,
|
||||
"source metadata file disappeared",
|
||||
RetryHint::Retryable,
|
||||
)),
|
||||
)
|
||||
}
|
||||
other => panic!("unexpected instruction {other:?}"),
|
||||
};
|
||||
mailbox.on_recv(id, Ok(reply)).await.unwrap();
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("runner must send a second SyncRegions request");
|
||||
manager.stop().await.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -354,7 +354,12 @@ impl RegionFlushTrigger {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
let max_txn_ops = self.table_metadata_manager.kv_backend().max_txn_ops();
|
||||
// A transaction limit bounds the batch size when available. Otherwise write one region per request.
|
||||
let max_txn_ops = self
|
||||
.table_metadata_manager
|
||||
.kv_backend()
|
||||
.txn_capability()
|
||||
.map_or(1, |txn| txn.max_ops.max(1));
|
||||
let batch_size = max_txn_ops.min(regions.len());
|
||||
debug!(
|
||||
"persisting {} region checkpoints for topic '{}', regions: {:?}",
|
||||
|
||||
@@ -20,7 +20,7 @@ use common_meta::key::TableMetadataManagerRef;
|
||||
use common_meta::key::table_route::TableRouteValue;
|
||||
use common_meta::region_keeper::{MemoryRegionKeeperRef, OperatingRegion};
|
||||
use common_meta::rpc::router::RegionRoute;
|
||||
use common_telemetry::{info, warn};
|
||||
use common_telemetry::{debug, info, warn};
|
||||
use snafu::ResultExt;
|
||||
use store_api::region_engine::{GrantedRegion, RegionRole};
|
||||
use store_api::storage::{RegionId, TableId};
|
||||
@@ -97,10 +97,20 @@ fn renew_region_lease_via_operating_regions(
|
||||
region_lease_info.candidate_lease_id = operating_region.candidate_lease_id;
|
||||
}
|
||||
if role != reported_role {
|
||||
info!(
|
||||
"The region {} on datanode {} is operating with role {:?}, but reported as {:?}",
|
||||
region_id, datanode_id, role, reported_role
|
||||
);
|
||||
// A candidate lease id with a reported Leader means a migration target that a catchup
|
||||
// promoted before the route switch, which is expected until the switch.
|
||||
if region_lease_info.candidate_lease_id.is_some() && reported_role == RegionRole::Leader
|
||||
{
|
||||
debug!(
|
||||
"The candidate region {} on datanode {} is operating with role {:?}, but reported as {:?}",
|
||||
region_id, datanode_id, role, reported_role
|
||||
);
|
||||
} else {
|
||||
info!(
|
||||
"The region {} on datanode {} is operating with role {:?}, but reported as {:?}",
|
||||
region_id, datanode_id, role, reported_role
|
||||
);
|
||||
}
|
||||
}
|
||||
return Some(region_lease_info);
|
||||
}
|
||||
@@ -291,7 +301,7 @@ impl RegionLeaseKeeper {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use common_meta::DatanodeId;
|
||||
use common_meta::key::TableMetadataManager;
|
||||
@@ -305,7 +315,10 @@ mod tests {
|
||||
use store_api::storage::RegionId;
|
||||
use table::metadata::TableInfo;
|
||||
|
||||
use super::{RegionLeaseKeeper, renew_region_lease_via_region_route};
|
||||
use super::{
|
||||
RegionLeaseKeeper, renew_region_lease_via_operating_regions,
|
||||
renew_region_lease_via_region_route,
|
||||
};
|
||||
use crate::region::lease_keeper::{RegionLeaseInfo, RenewRegionLeasesResponse};
|
||||
|
||||
fn new_test_keeper() -> RegionLeaseKeeper {
|
||||
@@ -317,6 +330,69 @@ mod tests {
|
||||
RegionLeaseKeeper::new(table_metadata_manager, opening_region_keeper)
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct LevelCapture(Arc<Mutex<Vec<tracing::Level>>>);
|
||||
|
||||
impl<S: tracing::Subscriber> tracing_subscriber::Layer<S> for LevelCapture {
|
||||
fn on_event(
|
||||
&self,
|
||||
event: &tracing::Event<'_>,
|
||||
_: tracing_subscriber::layer::Context<'_, S>,
|
||||
) {
|
||||
self.0.lock().unwrap().push(*event.metadata().level());
|
||||
}
|
||||
}
|
||||
|
||||
/// The expected mismatch of a migration target that a catchup promoted logs at debug; every
|
||||
/// other mismatch logs at info, and a matching role logs nothing.
|
||||
#[test]
|
||||
fn test_role_mismatch_log_level_of_operating_region() {
|
||||
use tracing::Level;
|
||||
use tracing_subscriber::layer::SubscriberExt;
|
||||
|
||||
let region_id = RegionId::new(1024, 1);
|
||||
let log_levels = |role, candidate_lease_id, reported_role, table_route_exists| {
|
||||
let capture = LevelCapture::default();
|
||||
let subscriber = tracing_subscriber::registry().with(capture.clone());
|
||||
let operating_regions = HashMap::from([(
|
||||
region_id,
|
||||
OperatingRegion {
|
||||
role,
|
||||
candidate_lease_id,
|
||||
},
|
||||
)]);
|
||||
tracing::subscriber::with_default(subscriber, || {
|
||||
renew_region_lease_via_operating_regions(
|
||||
&operating_regions,
|
||||
1,
|
||||
region_id,
|
||||
reported_role,
|
||||
table_route_exists,
|
||||
)
|
||||
.unwrap();
|
||||
});
|
||||
capture.0.lock().unwrap().clone()
|
||||
};
|
||||
let follower = RegionRole::Follower;
|
||||
let leader = RegionRole::Leader;
|
||||
|
||||
assert_eq!(
|
||||
log_levels(follower, Some(7), leader, true),
|
||||
vec![Level::DEBUG]
|
||||
);
|
||||
assert_eq!(log_levels(follower, None, leader, true), vec![Level::INFO]);
|
||||
assert_eq!(
|
||||
log_levels(follower, Some(7), leader, false),
|
||||
vec![Level::INFO]
|
||||
);
|
||||
assert_eq!(
|
||||
log_levels(follower, Some(7), RegionRole::DowngradingLeader, true),
|
||||
vec![Level::INFO]
|
||||
);
|
||||
assert!(log_levels(follower, Some(7), follower, true).is_empty());
|
||||
assert!(log_levels(leader, Some(7), leader, true).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_renew_region_lease_via_region_route() {
|
||||
let region_id = RegionId::new(1024, 1);
|
||||
|
||||
@@ -22,7 +22,8 @@ use common_meta::key::CACHE_KEY_PREFIXES;
|
||||
use common_meta::kv_backend::memory::MemoryKvBackend;
|
||||
use common_meta::kv_backend::txn::{Txn, TxnOp, TxnRequest, TxnResponse};
|
||||
use common_meta::kv_backend::{
|
||||
KvBackend, KvBackendRef, ResettableKvBackend, ResettableKvBackendRef, TxnService,
|
||||
KvBackend, KvBackendCapabilities, KvBackendRef, ResettableKvBackend, ResettableKvBackendRef,
|
||||
TxnCapability, TxnService,
|
||||
};
|
||||
use common_meta::range_stream::{DEFAULT_PAGE_SIZE, PaginationStream};
|
||||
use common_meta::rpc::KeyValue;
|
||||
@@ -166,6 +167,10 @@ impl LeaderCachedKvBackend {
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl KvBackend for LeaderCachedKvBackend {
|
||||
fn capabilities(&self) -> KvBackendCapabilities {
|
||||
self.store.capabilities()
|
||||
}
|
||||
|
||||
fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
@@ -376,8 +381,8 @@ impl TxnService for LeaderCachedKvBackend {
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
fn max_txn_ops(&self) -> usize {
|
||||
self.store.max_txn_ops()
|
||||
fn txn_capability(&self) -> Option<TxnCapability> {
|
||||
self.store.txn_capability()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -463,8 +468,8 @@ mod tests {
|
||||
res
|
||||
}
|
||||
|
||||
fn max_txn_ops(&self) -> usize {
|
||||
self.inner.max_txn_ops()
|
||||
fn txn_capability(&self) -> Option<TxnCapability> {
|
||||
self.inner.txn_capability()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -421,14 +421,12 @@ impl RegionEngine for MetricEngine {
|
||||
Ok(true) => {}
|
||||
Ok(false) => {
|
||||
// If the metadata region ignored the grant, the data region is not handed it, so
|
||||
// record it for the data region. If the data region ignored it, the data region
|
||||
// has already recorded it.
|
||||
// record it and extend the deadline for the data region, as an ignored Leader
|
||||
// lease does. If the data region ignored it, the data region has done both.
|
||||
if x == metadata_region_id {
|
||||
self.inner.mito.record_granted_lease(
|
||||
data_region_id,
|
||||
sent_at,
|
||||
candidate_lease_id,
|
||||
);
|
||||
let mito = &self.inner.mito;
|
||||
mito.record_granted_lease(data_region_id, sent_at, candidate_lease_id);
|
||||
mito.extend_leader_deadline(data_region_id, deadline);
|
||||
}
|
||||
return Ok(false);
|
||||
}
|
||||
@@ -539,6 +537,18 @@ impl RegionEngine for MetricEngine {
|
||||
}
|
||||
}
|
||||
|
||||
/// A physical region is a confirmed leader only if both regions of the pair are, since one
|
||||
/// may have been promoted without the other.
|
||||
fn is_confirmed_leader(&self, region_id: RegionId) -> Option<bool> {
|
||||
if !self.inner.is_physical_region(region_id) {
|
||||
return None;
|
||||
}
|
||||
let mito = &self.inner.mito;
|
||||
let metadata = mito.is_confirmed_leader(utils::to_metadata_region_id(region_id))?;
|
||||
let data = mito.is_confirmed_leader(utils::to_data_region_id(region_id))?;
|
||||
Some(metadata && data)
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
@@ -556,6 +566,17 @@ pub struct PutGroupResult {
|
||||
}
|
||||
|
||||
impl MetricEngine {
|
||||
/// Pauses compaction on the metadata half of a physical metric region.
|
||||
pub async fn pause_metadata_compaction(
|
||||
&self,
|
||||
physical_region: RegionId,
|
||||
) -> mito2::error::Result<mito2::compaction::CompactionGuard> {
|
||||
self.inner
|
||||
.mito
|
||||
.pause_compaction(crate::utils::to_metadata_region_id(physical_region))
|
||||
.await
|
||||
}
|
||||
|
||||
pub fn try_new(mito: MitoEngine, mut config: EngineConfig) -> Result<Self> {
|
||||
let metadata_region = MetadataRegion::new(mito.clone());
|
||||
let data_region = DataRegion::new(mito.clone());
|
||||
@@ -1115,6 +1136,157 @@ mod test {
|
||||
assert_eq!(engine.role(physical_region_id), Some(RegionRole::Leader));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_physical_region_is_confirmed_leader_only_after_both_leader_leases() {
|
||||
let env = TestEnv::new().await;
|
||||
env.init_metric_region().await;
|
||||
let (engine, mito) = (env.metric(), env.mito());
|
||||
mito.require_write_lease();
|
||||
mito.renew_node_lease(Instant::now() + LEASE);
|
||||
let physical_region_id = env.default_physical_region_id();
|
||||
let metadata_region_id = utils::to_metadata_region_id(physical_region_id);
|
||||
// A logical region has no role of its own.
|
||||
assert_eq!(
|
||||
engine.is_confirmed_leader(env.default_logical_region_id()),
|
||||
None
|
||||
);
|
||||
for region_id in [
|
||||
metadata_region_id,
|
||||
utils::to_data_region_id(physical_region_id),
|
||||
] {
|
||||
mito.set_region_role_state_gracefully(region_id, SettableRegionRoleState::Follower)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
let catchup = RegionCatchupRequest {
|
||||
set_writable: true,
|
||||
..Default::default()
|
||||
};
|
||||
engine
|
||||
.handle_batch_catchup_requests(1, vec![(physical_region_id, catchup)])
|
||||
.await
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.for_each(|(_, result)| {
|
||||
result.unwrap();
|
||||
});
|
||||
assert_eq!(engine.role(physical_region_id), Some(RegionRole::Leader));
|
||||
assert_eq!(engine.is_confirmed_leader(physical_region_id), Some(false));
|
||||
|
||||
// A candidate lease leaves both waiting regions writable, and the physical region
|
||||
// unconfirmed, so an upgrade still catches it up.
|
||||
let sent_at = Instant::now();
|
||||
assert!(
|
||||
engine
|
||||
.set_region_role_with_lease(
|
||||
physical_region_id,
|
||||
RegionRole::Follower,
|
||||
sent_at,
|
||||
sent_at + LEASE,
|
||||
Some(7),
|
||||
)
|
||||
.unwrap()
|
||||
);
|
||||
for region_id in [
|
||||
metadata_region_id,
|
||||
utils::to_data_region_id(physical_region_id),
|
||||
] {
|
||||
assert_eq!(mito.role(region_id), Some(RegionRole::Leader));
|
||||
}
|
||||
assert_eq!(engine.role(physical_region_id), Some(RegionRole::Leader));
|
||||
assert_eq!(engine.is_confirmed_leader(physical_region_id), Some(false));
|
||||
|
||||
// The data region still waits after the metadata region received its lease.
|
||||
mito.set_region_role_with_lease(
|
||||
metadata_region_id,
|
||||
RegionRole::Leader,
|
||||
sent_at,
|
||||
sent_at + LEASE,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(engine.is_confirmed_leader(physical_region_id), Some(false));
|
||||
|
||||
engine
|
||||
.set_region_role_with_lease(
|
||||
physical_region_id,
|
||||
RegionRole::Leader,
|
||||
sent_at,
|
||||
sent_at + LEASE,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(engine.is_confirmed_leader(physical_region_id), Some(true));
|
||||
|
||||
// A confirmed data region alone does not make the physical region confirmed.
|
||||
mito.set_region_role(metadata_region_id, RegionRole::Follower)
|
||||
.unwrap();
|
||||
assert_eq!(engine.is_confirmed_leader(physical_region_id), Some(false));
|
||||
}
|
||||
|
||||
/// A physical Leader lease that the metadata region ignores is still recorded for the data
|
||||
/// region and extends its deadline.
|
||||
#[tokio::test]
|
||||
async fn test_lease_ignored_by_metadata_region_extends_data_deadline() {
|
||||
let env = TestEnv::new().await;
|
||||
env.init_metric_region().await;
|
||||
let (engine, mito) = (env.metric(), env.mito());
|
||||
let physical_region_id = env.default_physical_region_id();
|
||||
let metadata_region_id = utils::to_metadata_region_id(physical_region_id);
|
||||
let data_region_id = utils::to_data_region_id(physical_region_id);
|
||||
let start = Instant::now();
|
||||
mito.require_write_lease();
|
||||
mito.renew_node_lease(start + LEASE);
|
||||
mito.set_region_role_state_gracefully(data_region_id, SettableRegionRoleState::Follower)
|
||||
.await
|
||||
.unwrap();
|
||||
// The data region's catchup sets its deadline to the node lease's.
|
||||
let catchup = RegionCatchupRequest {
|
||||
set_writable: true,
|
||||
..Default::default()
|
||||
};
|
||||
mito.handle_request(data_region_id, RegionRequest::Catchup(catchup))
|
||||
.await
|
||||
.unwrap();
|
||||
mito.renew_node_lease(start + 10 * LEASE);
|
||||
let sent_at = Instant::now();
|
||||
mito.set_region_role_state_gracefully(
|
||||
metadata_region_id,
|
||||
SettableRegionRoleState::Follower,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
// The metadata region was downgraded after `sent_at`, so it ignores the lease.
|
||||
let promoted = engine
|
||||
.set_region_role_with_lease(
|
||||
physical_region_id,
|
||||
RegionRole::Leader,
|
||||
sent_at,
|
||||
start + 5 * LEASE,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(!promoted);
|
||||
|
||||
// Past the deadline the data region's catchup set, before the lease's.
|
||||
mito.freeze_lease_clock(start + 2 * LEASE);
|
||||
engine
|
||||
.handle_request(
|
||||
env.default_logical_region_id(),
|
||||
RegionRequest::Put(RegionPutRequest {
|
||||
skip_wal: false,
|
||||
rows: Rows {
|
||||
schema: row_schema_with_tags(&["job"]),
|
||||
rows: build_rows(1, 5),
|
||||
},
|
||||
hint: None,
|
||||
partition_expr_version: None,
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_candidate_lease_id_reaches_metadata_and_data_regions() {
|
||||
let env = TestEnv::new().await;
|
||||
|
||||
@@ -74,10 +74,14 @@ pub fn set_data_region_options(options: &mut HashMap<String, String>) {
|
||||
let legacy_encoding = options.remove(MEMTABLE_PARTITION_TREE_PRIMARY_KEY_ENCODING);
|
||||
options.retain(|k, _| !k.starts_with(LEGACY_PARTITION_TREE_OPTION_PREFIX));
|
||||
|
||||
// Set memtable options for the data region. Bulk memtable produces
|
||||
// flat-encoded ranges, so the SST format must be flat to match.
|
||||
// Bulk memtables support both flat Parquet and Narthex samples. Preserve
|
||||
// explicit Narthex storage while keeping the existing Parquet default.
|
||||
options.insert("memtable.type".to_string(), "bulk".to_string());
|
||||
options.insert("sst_format".to_string(), "flat".to_string());
|
||||
let sst_format = match options.get("sst_format").map(String::as_str) {
|
||||
Some("narthex") => "narthex",
|
||||
_ => "flat",
|
||||
};
|
||||
options.insert("sst_format".to_string(), sst_format.to_string());
|
||||
|
||||
// Decide the top-level primary key encoding: caller-supplied top-level key wins,
|
||||
// then extracted legacy value, then the `sparse` default.
|
||||
@@ -157,6 +161,16 @@ impl TryFrom<&HashMap<String, String>> for PhysicalRegionOptions {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_set_data_region_options_preserves_narthex_storage() {
|
||||
let format = "narthex";
|
||||
let mut options = HashMap::from([("sst_format".to_string(), format.to_string())]);
|
||||
set_data_region_options(&mut options);
|
||||
assert_eq!(options.get("sst_format").unwrap(), "narthex");
|
||||
assert_eq!(options.get("memtable.type").unwrap(), "bulk");
|
||||
assert_eq!(options.get(PRIMARY_KEY_ENCODING).unwrap(), "sparse");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_set_data_region_options_should_remove_metric_engine_options() {
|
||||
let mut options = HashMap::new();
|
||||
|
||||
@@ -15,16 +15,17 @@
|
||||
use std::time::Instant;
|
||||
|
||||
use common_error::ext::BoxedError;
|
||||
use common_telemetry::info;
|
||||
use common_telemetry::{info, warn};
|
||||
use mito2::manifest::action::RegionEdit;
|
||||
use snafu::{OptionExt, ResultExt, ensure};
|
||||
use mito2::region::MitoRegion;
|
||||
use snafu::{OptionExt, ResultExt};
|
||||
use store_api::region_engine::{MitoCopyRegionFromRequest, SyncRegionFromResponse};
|
||||
use store_api::storage::RegionId;
|
||||
use store_api::storage::{FileId, RegionId};
|
||||
|
||||
use crate::engine::MetricEngineInner;
|
||||
use crate::error::{
|
||||
MissingFilesSnafu, MitoCopyRegionFromOperationSnafu, MitoEditRegionSnafu,
|
||||
PhysicalRegionNotFoundSnafu, Result,
|
||||
MitoPauseCompactionOperationSnafu, PhysicalRegionNotFoundSnafu, Result,
|
||||
};
|
||||
use crate::utils;
|
||||
|
||||
@@ -53,6 +54,23 @@ impl MetricEngineInner {
|
||||
source_region_id, region_id, parallelism
|
||||
);
|
||||
|
||||
// Cleanup removes the original copied file IDs, so compaction must not replace them.
|
||||
let guard = self
|
||||
.mito
|
||||
.pause_compaction(target_metadata_region_id)
|
||||
.await
|
||||
.map_err(BoxedError::new)
|
||||
.context(MitoPauseCompactionOperationSnafu {
|
||||
region_id: target_metadata_region_id,
|
||||
})?;
|
||||
let target_region = self.mito.find_region(target_metadata_region_id).context(
|
||||
PhysicalRegionNotFoundSnafu {
|
||||
region_id: target_metadata_region_id,
|
||||
},
|
||||
)?;
|
||||
// Under the compaction guard, only SSTs present before import can retain
|
||||
// source keys after we remove this attempt's copied files.
|
||||
let had_ssts = target_region.has_ssts();
|
||||
let res = self
|
||||
.mito
|
||||
.copy_region_from(
|
||||
@@ -69,6 +87,20 @@ impl MetricEngineInner {
|
||||
target_region_id: target_metadata_region_id,
|
||||
})?;
|
||||
|
||||
if !res.copied_file_ids.is_empty() {
|
||||
self.transform_imported_files(
|
||||
&target_region,
|
||||
source_data_region_id,
|
||||
&res.copied_file_ids,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
if had_ssts && target_region.has_ssts() {
|
||||
self.metadata_region
|
||||
.remove_imported_keys(target_metadata_region_id, source_data_region_id)
|
||||
.await?;
|
||||
}
|
||||
drop(guard);
|
||||
if res.copied_file_ids.is_empty() {
|
||||
info!(
|
||||
"No files were copied from source region {} to target region {}, copied file ids are empty",
|
||||
@@ -81,66 +113,6 @@ impl MetricEngineInner {
|
||||
});
|
||||
}
|
||||
|
||||
let target_region = self.mito.find_region(target_metadata_region_id).context(
|
||||
PhysicalRegionNotFoundSnafu {
|
||||
region_id: target_metadata_region_id,
|
||||
},
|
||||
)?;
|
||||
let files_to_remove = target_region.file_metas(&res.copied_file_ids).await;
|
||||
let missing_file_ids = res
|
||||
.copied_file_ids
|
||||
.iter()
|
||||
.zip(&files_to_remove)
|
||||
.filter_map(|(file_id, maybe_meta)| {
|
||||
if maybe_meta.is_none() {
|
||||
Some(*file_id)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
// `copy_region_from` does not trigger compaction,
|
||||
// so there should be no files removed and thus no missing files.
|
||||
ensure!(
|
||||
missing_file_ids.is_empty(),
|
||||
MissingFilesSnafu {
|
||||
region_id: target_metadata_region_id,
|
||||
file_ids: missing_file_ids,
|
||||
}
|
||||
);
|
||||
let files_to_remove = files_to_remove.into_iter().flatten().collect::<Vec<_>>();
|
||||
// Transform the logical region metadata of the target data region.
|
||||
self.metadata_region
|
||||
.transform_logical_region_metadata(target_data_region_id, source_data_region_id)
|
||||
.await?;
|
||||
|
||||
let edit = RegionEdit {
|
||||
files_to_add: vec![],
|
||||
files_to_remove: files_to_remove.clone(),
|
||||
timestamp_ms: Some(chrono::Utc::now().timestamp_millis()),
|
||||
compaction_time_window: None,
|
||||
flushed_entry_id: None,
|
||||
flushed_sequence: None,
|
||||
committed_sequence: None,
|
||||
..Default::default()
|
||||
};
|
||||
self.mito
|
||||
.edit_region(target_metadata_region_id, edit)
|
||||
.await
|
||||
.map_err(BoxedError::new)
|
||||
.context(MitoEditRegionSnafu {
|
||||
region_id: target_metadata_region_id,
|
||||
})?;
|
||||
info!(
|
||||
"Successfully edit metadata region: {} after syncing from source metadata region: {}, files to remove: {:?}",
|
||||
target_metadata_region_id,
|
||||
source_metadata_region_id,
|
||||
files_to_remove
|
||||
.iter()
|
||||
.map(|meta| meta.file_id)
|
||||
.collect::<Vec<_>>(),
|
||||
);
|
||||
|
||||
let now = Instant::now();
|
||||
// Always recover states from the target metadata region after syncing
|
||||
// from the source metadata region.
|
||||
@@ -171,6 +143,62 @@ impl MetricEngineInner {
|
||||
new_opened_logical_region_ids,
|
||||
})
|
||||
}
|
||||
|
||||
async fn transform_imported_files(
|
||||
&self,
|
||||
target_region: &MitoRegion,
|
||||
source_data_region_id: RegionId,
|
||||
file_ids: &[FileId],
|
||||
) -> Result<()> {
|
||||
let target_metadata_region_id = target_region.region_id();
|
||||
let target_data_region_id = utils::to_data_region_id(target_metadata_region_id);
|
||||
let files_to_remove = target_region.file_metas(file_ids).await;
|
||||
let missing_file_ids = file_ids
|
||||
.iter()
|
||||
.zip(&files_to_remove)
|
||||
.filter_map(|(file_id, maybe_meta)| {
|
||||
if maybe_meta.is_none() {
|
||||
Some(*file_id)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let transform = if missing_file_ids.is_empty() {
|
||||
self.metadata_region
|
||||
.transform_logical_region_metadata(target_data_region_id, source_data_region_id)
|
||||
.await
|
||||
} else {
|
||||
MissingFilesSnafu {
|
||||
region_id: target_metadata_region_id,
|
||||
file_ids: missing_file_ids,
|
||||
}
|
||||
.fail()
|
||||
};
|
||||
let files_to_remove: Vec<_> = files_to_remove.into_iter().flatten().collect();
|
||||
if !files_to_remove.is_empty() {
|
||||
let edit = RegionEdit {
|
||||
files_to_remove,
|
||||
timestamp_ms: Some(chrono::Utc::now().timestamp_millis()),
|
||||
..Default::default()
|
||||
};
|
||||
let cleanup = self
|
||||
.mito
|
||||
.edit_region(target_metadata_region_id, edit)
|
||||
.await
|
||||
.map_err(BoxedError::new)
|
||||
.context(MitoEditRegionSnafu {
|
||||
region_id: target_metadata_region_id,
|
||||
});
|
||||
if let Err(err) = cleanup {
|
||||
if transform.is_ok() {
|
||||
return Err(err);
|
||||
}
|
||||
warn!(err; "Failed to remove copied SSTs from {target_metadata_region_id} after sync failed");
|
||||
}
|
||||
}
|
||||
transform
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -207,6 +235,260 @@ mod tests {
|
||||
assert_eq!(columns, expected_columns);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_metadata_sync_pause_on_missing_target() {
|
||||
let env = TestEnv::new().await;
|
||||
let source = env.default_physical_region_id();
|
||||
let target = RegionId::new(source.table_id(), source.region_number() + 1);
|
||||
let target_metadata = crate::utils::to_metadata_region_id(target);
|
||||
let err = env
|
||||
.metric()
|
||||
.inner
|
||||
.sync_region_from_region(target, source, 1)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(StatusCode::RegionNotFound, err.status_code());
|
||||
let crate::error::Error::MitoPauseCompactionOperation {
|
||||
region_id, source, ..
|
||||
} = err
|
||||
else {
|
||||
panic!("unexpected sync error: {err:?}");
|
||||
};
|
||||
assert_eq!(target_metadata, region_id);
|
||||
assert!(matches!(
|
||||
source.into_inner().as_any().downcast_ref::<mito2::error::Error>(),
|
||||
Some(mito2::error::Error::RegionNotFound { region_id, .. }) if *region_id == target_metadata
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_metadata_sync_blocks_compaction_until_cleanup() {
|
||||
let env = TestEnv::new().await;
|
||||
env.init_metric_region().await;
|
||||
let source = env.default_physical_region_id();
|
||||
let logical = env.default_logical_region_id();
|
||||
let target = RegionId::new(source.table_id(), 7);
|
||||
env.create_physical_region(target, &TestEnv::default_table_dir(), vec![])
|
||||
.await;
|
||||
// Leave target rows in the memtable so the intervening flush creates an SST.
|
||||
let existing = RegionId::new(4, target.region_number());
|
||||
env.create_logical_region(target, existing).await;
|
||||
let metric = env.metric();
|
||||
metric
|
||||
.handle_request(source, RegionRequest::Flush(Default::default()))
|
||||
.await
|
||||
.unwrap();
|
||||
let target_metadata = crate::utils::to_metadata_region_id(target);
|
||||
let metadata = &metric.inner.metadata_region;
|
||||
let mito = env.mito();
|
||||
|
||||
// A source-numbered orphan column in the target memtable makes an unnecessary
|
||||
// fallback scan observable: the transform ignores it, but the fallback deletes it.
|
||||
let probe =
|
||||
MetadataRegion::concat_column_key(RegionId::new(99, source.region_number()), "probe");
|
||||
let put = MetadataRegion::build_put_request_from_iter(std::iter::once((
|
||||
probe.clone(),
|
||||
String::new(),
|
||||
)));
|
||||
mito.handle_request(target_metadata, RegionRequest::Put(put))
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!mito.find_region(target_metadata).unwrap().has_ssts());
|
||||
|
||||
// Hold the transform at its metadata write. The copied source marker is
|
||||
// observable through a key-only scan while the sync waits for the lock.
|
||||
let observe = metadata.with_writes_paused(target_metadata, async {
|
||||
tokio::time::timeout(std::time::Duration::from_secs(10), async {
|
||||
while !metadata
|
||||
.logical_regions(target)
|
||||
.await
|
||||
.unwrap()
|
||||
.contains(&logical)
|
||||
{
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
mito.handle_request(target_metadata, RegionRequest::Flush(Default::default()))
|
||||
.await
|
||||
.unwrap();
|
||||
let err = mito
|
||||
.handle_request(target_metadata, RegionRequest::Compact(Default::default()))
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(matches!(
|
||||
err.into_inner()
|
||||
.as_any()
|
||||
.downcast_ref::<mito2::error::Error>(),
|
||||
Some(mito2::error::Error::CompactionCancelled { .. })
|
||||
));
|
||||
});
|
||||
let sync = metric.sync_region(
|
||||
target,
|
||||
SyncRegionFromRequest::FromRegion {
|
||||
source_region_id: source,
|
||||
parallelism: 1,
|
||||
},
|
||||
);
|
||||
let ((), result) = tokio::join!(observe, sync);
|
||||
result.unwrap();
|
||||
let remapped = RegionId::new(logical.table_id(), target.region_number());
|
||||
let mut recovered = metadata.logical_regions(target).await.unwrap();
|
||||
recovered.sort_unstable();
|
||||
assert_eq!(recovered, [remapped, existing]);
|
||||
assert!(mito.find_region(target_metadata).unwrap().has_ssts());
|
||||
assert!(
|
||||
metadata
|
||||
.get(target_metadata, &probe)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_some()
|
||||
);
|
||||
mito.handle_request(target_metadata, RegionRequest::Compact(Default::default()))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[rstest::rstest]
|
||||
#[case::transform_fails(true, false)]
|
||||
#[case::both_fail(true, true)]
|
||||
#[case::cleanup_fails(false, true)]
|
||||
#[tokio::test]
|
||||
async fn test_sync_cleans_imported_files_on_error(
|
||||
#[case] invalid_column: bool,
|
||||
#[case] fail_cleanup: bool,
|
||||
) {
|
||||
use mito2::test_util::{DeltaFaults, TestEnv as MitoTestEnv};
|
||||
use store_api::region_engine::MitoCopyRegionFromRequest;
|
||||
|
||||
let faults = DeltaFaults::default();
|
||||
let mito_env = MitoTestEnv::with_prefix("sync-cleanup")
|
||||
.await
|
||||
.with_mock_layer(faults.layer());
|
||||
let env = TestEnv::with_mito_env(mito_env).await;
|
||||
env.init_metric_region().await;
|
||||
let source = env.default_physical_region_id();
|
||||
let logical = env.default_logical_region_id();
|
||||
let target = RegionId::new(source.table_id(), 7);
|
||||
env.create_physical_region(target, &TestEnv::default_table_dir(), vec![])
|
||||
.await;
|
||||
let source_meta = crate::utils::to_metadata_region_id(source);
|
||||
let target_meta = crate::utils::to_metadata_region_id(target);
|
||||
let mito = env.mito();
|
||||
let source_guard = mito.pause_compaction(source_meta).await.unwrap();
|
||||
if invalid_column {
|
||||
let entries = [(format!("__column_{}_!", logical.as_u64()), String::new())];
|
||||
let put = MetadataRegion::build_put_request_from_iter(entries.into_iter());
|
||||
mito.handle_request(source_meta, RegionRequest::Put(put))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
mito.handle_request(source_meta, RegionRequest::Flush(Default::default()))
|
||||
.await
|
||||
.unwrap();
|
||||
if !invalid_column {
|
||||
// Give compaction distinct flushed SSTs without changing the source schema.
|
||||
for _ in 0..4 {
|
||||
let marker = (MetadataRegion::concat_region_key(logical), String::new());
|
||||
let put = MetadataRegion::build_put_request_from_iter(std::iter::once(marker));
|
||||
mito.handle_request(source_meta, RegionRequest::Put(put))
|
||||
.await
|
||||
.unwrap();
|
||||
mito2::test_util::flush_region(&mito, source_meta, None).await;
|
||||
}
|
||||
}
|
||||
// Model a retry after import. The next manifest write will be the cleanup edit.
|
||||
let imported = mito
|
||||
.copy_region_from(
|
||||
target_meta,
|
||||
MitoCopyRegionFromRequest {
|
||||
source_region_id: source_meta,
|
||||
parallelism: 1,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!imported.copied_file_ids.is_empty());
|
||||
if fail_cleanup {
|
||||
faults.fail_next_write();
|
||||
}
|
||||
let err = env
|
||||
.metric()
|
||||
.inner
|
||||
.sync_region_from_region(target, source, 1)
|
||||
.await
|
||||
.unwrap_err();
|
||||
if invalid_column {
|
||||
assert!(
|
||||
matches!(err, crate::error::Error::DecodeColumnValue { .. }),
|
||||
"{err}"
|
||||
);
|
||||
} else {
|
||||
assert!(
|
||||
matches!(err, crate::error::Error::MitoEditRegion { .. }),
|
||||
"{err}"
|
||||
);
|
||||
}
|
||||
if !invalid_column {
|
||||
drop(source_guard);
|
||||
mito.handle_request(source_meta, RegionRequest::Compact(Default::default()))
|
||||
.await
|
||||
.unwrap();
|
||||
let source_region = mito.find_region(source_meta).unwrap();
|
||||
assert!(
|
||||
source_region
|
||||
.file_metas(&imported.copied_file_ids)
|
||||
.await
|
||||
.iter()
|
||||
.any(Option::is_none)
|
||||
);
|
||||
// An uncertain manifest edit closes the target. Reopen it before retrying.
|
||||
mito.handle_request(
|
||||
target_meta,
|
||||
RegionRequest::Open(RegionOpenRequest {
|
||||
engine: mito2::engine::MITO_ENGINE_NAME.into(),
|
||||
table_dir: TestEnv::default_table_dir(),
|
||||
path_type: PathType::Metadata,
|
||||
options: Default::default(),
|
||||
skip_wal_replay: false,
|
||||
checkpoint: None,
|
||||
requirements: Default::default(),
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
mito.set_region_role(target_meta, store_api::region_engine::RegionRole::Leader)
|
||||
.unwrap();
|
||||
env.metric()
|
||||
.inner
|
||||
.sync_region_from_region(target, source, 1)
|
||||
.await
|
||||
.unwrap();
|
||||
let metadata = env.metadata_region();
|
||||
let remapped = RegionId::new(logical.table_id(), target.region_number());
|
||||
assert_eq!(metadata.logical_regions(target).await.unwrap(), [remapped]);
|
||||
assert_logical_table_columns(&metadata, target, logical, &[]).await;
|
||||
assert_logical_table_columns(
|
||||
&metadata,
|
||||
target,
|
||||
remapped,
|
||||
&["greptime_timestamp", "greptime_value", "job"],
|
||||
)
|
||||
.await;
|
||||
}
|
||||
if !fail_cleanup {
|
||||
let region = mito.find_region(target_meta).unwrap();
|
||||
assert!(
|
||||
region
|
||||
.file_metas(&imported.copied_file_ids)
|
||||
.await
|
||||
.iter()
|
||||
.all(Option::is_none)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_sync_region_from_region() {
|
||||
common_telemetry::init_default_ut_logging();
|
||||
|
||||
@@ -149,6 +149,14 @@ pub enum Error {
|
||||
target_region_id: RegionId,
|
||||
},
|
||||
|
||||
#[snafu(display("Failed to pause compaction for region {}", region_id))]
|
||||
MitoPauseCompactionOperation {
|
||||
region_id: RegionId,
|
||||
source: BoxedError,
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display("Mito edit region operation fails, region id: {}", region_id))]
|
||||
MitoEditRegion {
|
||||
region_id: RegionId,
|
||||
@@ -452,8 +460,8 @@ impl ErrorExt for Error {
|
||||
|
||||
ForbiddenPhysicalAlter { .. }
|
||||
| ForbiddenPhysicalWrite { .. }
|
||||
| UnsupportedRegionRequest { .. }
|
||||
| MissingFiles { .. } => StatusCode::Unsupported,
|
||||
| UnsupportedRegionRequest { .. } => StatusCode::Unsupported,
|
||||
MissingFiles { .. } => StatusCode::StorageUnavailable,
|
||||
|
||||
DeserializeColumnMetadata { .. }
|
||||
| SerializeColumnMetadata { .. }
|
||||
@@ -488,6 +496,7 @@ impl ErrorExt for Error {
|
||||
| BatchOpenMitoRegion { source, .. }
|
||||
| BatchCatchupMitoRegion { source, .. }
|
||||
| MitoCopyRegionFromOperation { source, .. }
|
||||
| MitoPauseCompactionOperation { source, .. }
|
||||
| MitoEditRegion { source, .. } => source.status_code(),
|
||||
|
||||
EncodePrimaryKey { source, .. } => source.status_code(),
|
||||
@@ -510,6 +519,7 @@ impl ErrorExt for Error {
|
||||
use Error::*;
|
||||
|
||||
match self {
|
||||
MissingFiles { .. } => RetryHint::Retryable,
|
||||
PhysicalRegionNotFound { .. } | LogicalRegionNotFound { .. } => {
|
||||
RetryHint::RetryAfterRouteRefresh
|
||||
}
|
||||
@@ -527,6 +537,7 @@ impl ErrorExt for Error {
|
||||
| MitoSyncOperation { source, .. }
|
||||
| MitoEnterStagingOperation { source, .. }
|
||||
| MitoCopyRegionFromOperation { source, .. }
|
||||
| MitoPauseCompactionOperation { source, .. }
|
||||
| MitoEditRegion { source, .. } => source.retry_hint(),
|
||||
|
||||
EncodePrimaryKey { source, .. } => source.retry_hint(),
|
||||
@@ -543,6 +554,38 @@ impl ErrorExt for Error {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_metadata_sync_missing_files_instruction_retry_hint() {
|
||||
use common_meta::instruction::InstructionError;
|
||||
use snafu::IntoError;
|
||||
|
||||
let source = RegionId::new(1, 1);
|
||||
let target = RegionId::new(1, 2);
|
||||
let missing_source = mito2::error::MetadataCopyFileNotFoundSnafu {
|
||||
path: "table/data.parquet",
|
||||
}
|
||||
.into_error(object_store::Error::new(
|
||||
object_store::ErrorKind::NotFound,
|
||||
"missing",
|
||||
));
|
||||
for err in [
|
||||
MitoCopyRegionFromOperationSnafu {
|
||||
source_region_id: source,
|
||||
target_region_id: target,
|
||||
}
|
||||
.into_error(BoxedError::new(missing_source)),
|
||||
MissingFilesSnafu {
|
||||
region_id: target,
|
||||
file_ids: vec![FileId::random()],
|
||||
}
|
||||
.build(),
|
||||
] {
|
||||
let reply = InstructionError::from_error(&err);
|
||||
assert_eq!(reply.code, StatusCode::StorageUnavailable);
|
||||
assert_eq!(reply.retry_hint, RetryHint::Retryable);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_missing_region_retry_hints() {
|
||||
let region_id = RegionId::new(1024, 1);
|
||||
|
||||
@@ -484,6 +484,17 @@ impl MetadataRegion {
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) async fn with_writes_paused(
|
||||
&self,
|
||||
metadata_region_id: RegionId,
|
||||
f: impl Future<Output = ()>,
|
||||
) {
|
||||
let lease = self.cache_access_lock(metadata_region_id);
|
||||
let _guard = lease.read().await;
|
||||
f.await;
|
||||
}
|
||||
|
||||
/// Acquires the cache access lock lease for `metadata_region_id`.
|
||||
///
|
||||
/// The lease must be kept alive for as long as any guard taken from it.
|
||||
@@ -546,6 +557,41 @@ impl MetadataRegion {
|
||||
.await
|
||||
}
|
||||
|
||||
/// Removes source markers and columns left in the target by a previous metadata import.
|
||||
pub(crate) async fn remove_imported_keys(
|
||||
&self,
|
||||
target_meta: RegionId,
|
||||
source: RegionId,
|
||||
) -> Result<()> {
|
||||
let request = ScanRequest {
|
||||
projection: Some(vec![METADATA_SCHEMA_KEY_COLUMN_INDEX]),
|
||||
..Default::default()
|
||||
};
|
||||
let mut stream = self
|
||||
.mito
|
||||
.scan_to_stream(target_meta, request)
|
||||
.await
|
||||
.context(MitoReadOperationSnafu)?;
|
||||
while let Some(batch) = stream
|
||||
.try_next()
|
||||
.await
|
||||
.context(CollectRecordBatchStreamSnafu)?
|
||||
{
|
||||
let mut keys = decode_record_batch_to_key(batch);
|
||||
keys.retain(|key| {
|
||||
let id = Self::parse_region_key(key)
|
||||
.or_else(|| Self::split_column_key(key).map(|(id, _)| id));
|
||||
id.filter(|raw| matches!(raw.as_bytes(), [b'0'] | [b'1'..=b'9', ..]))
|
||||
.and_then(|raw| raw.parse::<u64>().ok())
|
||||
.is_some_and(|id| RegionId::from(id).region_number() == source.region_number())
|
||||
});
|
||||
if !keys.is_empty() {
|
||||
self.delete(target_meta, &keys).await?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Delete the given keys. For performance consideration, this method
|
||||
/// doesn't check if those keys exist or not.
|
||||
async fn delete(&self, metadata_region_id: RegionId, keys: &[String]) -> Result<()> {
|
||||
|
||||
+37
-4
@@ -49,6 +49,10 @@ of one request to several regions (one message per worker) → worker loop
|
||||
writes SSTs via `access_layer.rs` and appends a `RegionEdit` to the manifest
|
||||
(`manifest/manager.rs`).
|
||||
|
||||
When reconstructing primary key bytes, follow the writer's ordering. Mito encodes
|
||||
raw tags in declared primary key order. Metric-engine sparse keys encode table ID
|
||||
and TSID first, then non-null labels in label-name order.
|
||||
|
||||
## Read path
|
||||
|
||||
`MitoEngine::handle_query` (`engine.rs`) → `read/scan_region.rs` takes an
|
||||
@@ -56,6 +60,10 @@ immutable `Version` (`region/version.rs`) → scans memtables and Parquet SSTs
|
||||
(`sst/parquet.rs`) → merges (`read/`) and dedups by sequence → projected,
|
||||
filtered `RecordBatch` stream.
|
||||
|
||||
Compaction SST scans share a read path. Multi-region compaction retains raw
|
||||
versions and routes each row before merging. Sparse routing temporarily
|
||||
materializes only the columns used by the partition rule.
|
||||
|
||||
Internal series merges use the query runtime pool forwarded through
|
||||
`QueryScanContext`; reader and output-batch accounting uses the separate scan
|
||||
memory tracker. Direct scanner callers default to an unbounded operator pool.
|
||||
@@ -123,9 +131,21 @@ Tests live next to the code as `*_test.rs` (e.g. `src/mito2/src/engine/flush_tes
|
||||
|
||||
## Gotchas
|
||||
|
||||
- Parquet versus Narthex storage is fixed at region creation. ALTER cannot cross
|
||||
that boundary; COPY, remap, and imported edits must reject mismatches before
|
||||
publication. Readers and compaction select storage from region options, not
|
||||
by inspecting individual files. Parquet flat/primary-key layouts may coexist.
|
||||
|
||||
- Parquet row groups have uniform row counts except for the final group
|
||||
(`sst/parquet/row_selection.rs`). Memory-pressure flushing must not create
|
||||
arbitrary partial groups: readers and index row IDs rely on this layout.
|
||||
- Append-mode Narthex raw-series reads apply LastRow dedup after merging;
|
||||
non-append reads use the configured merge mode, and batch reads retain append
|
||||
semantics. Physical COPY follows Parquet's
|
||||
untrusted source-sequence semantics; repartition still assigns admission sequences.
|
||||
The region worker owns COPY locks; task guards hold them through publication and
|
||||
installation so retries cannot race failure cleanup, including across region reopen.
|
||||
The last active or queued task removes its lock entry, including on cancellation.
|
||||
- Sequence numbers are strictly increasing per region; dedup and snapshot reads
|
||||
depend on this. Do not change assignment lightly.
|
||||
- Manifest version is monotonic — never reset or skip it. Staging takes no version:
|
||||
@@ -140,7 +160,9 @@ Tests live next to the code as `*_test.rs` (e.g. `src/mito2/src/engine/flush_tes
|
||||
it until the worker swaps in an instance reloaded from the new manifest
|
||||
(`worker/handle_reload.rs`). A tail replay round that fails while the storage holds a newer
|
||||
manifest fences a writable leader the same way. Never await a worker sender while holding a
|
||||
manifest guard.
|
||||
manifest guard. The catchup commit (`ManifestContext::commit_catchup`) is the exception: it
|
||||
commits as a Follower without the deadline check, and a conflict fails the catchup retryably
|
||||
without fencing the region; a retry reopens it from the newer manifest.
|
||||
- Pending tails (`RegionManifest::pending_tails`) are WAL ranges a region still has
|
||||
to recover; the flushed entry id never prunes them. Opening a region replays its
|
||||
WAL after `RegionManifest::wal_replay_start`. The WAL releases at open, after
|
||||
@@ -219,11 +241,22 @@ Tests live next to the code as `*_test.rs` (e.g. `src/mito2/src/engine/flush_tes
|
||||
`ManifestContext::update_locked` refuses its commits unless they are staged or the region is
|
||||
downgrading (a close that must flush downgrades first); only a replay of tails
|
||||
(`TailsEditor::Replay`) skips the check, a discard does not, and ending staging checks it
|
||||
before `commit_staged_locked`. No flush or compaction trigger starts work for a waiting region except
|
||||
a downgrade's flush. The lease that ends the wait wakes the worker
|
||||
before `commit_staged_locked`. `ManifestContext::commit_catchup` commits an empty edit as a
|
||||
Follower; fire its hook only after every manifest guard is dropped, including the old instance's
|
||||
read guard held by `handle_caught_up_again`. No flush or compaction trigger starts work for a
|
||||
waiting region except a downgrade's flush. The lease that ends the wait wakes the worker
|
||||
(`handle_leader_lease_wait_ended`) to schedule the flushes the wait deferred and, only if the
|
||||
region is then a writable leader, start a compaction, build missing indexes, re-issue the
|
||||
index build retries the wait refused and persist backfilled metadata.
|
||||
index build retries the wait refused and persist backfilled metadata. A catchup of a waiting
|
||||
region catches it up again into an unregistered replacement while the region stays registered,
|
||||
demoted unless it is in a transient leader state. The replacement replaces it only if the
|
||||
replay succeeds, the region took no write and made no commit meanwhile and, for a catchup that
|
||||
makes it writable, the replacement's catchup commit succeeds; otherwise the region keeps its
|
||||
memtable for the next Leader lease (`catch_up_again`, `handle_caught_up_again`); the datanode
|
||||
upgrade handler sends that catchup unless `RegionEngine::is_confirmed_leader` is true, so an
|
||||
engine wrapping mito must implement that method from mito's answers (the metric engine requires
|
||||
both regions of the pair). A Follower lease that carries a `candidate_lease_id` leaves a waiting
|
||||
region alone (`ManifestContext::demote_candidate`); other Follower leases demote it.
|
||||
- The latest lease each region received (`GrantedLeases` in `lease.rs`) lives outside the
|
||||
region instance, so a reopen during catchup keeps it. Every path that removes a region from
|
||||
a worker's region map must also remove its record and its kept index build retries:
|
||||
|
||||
@@ -30,7 +30,7 @@ use futures::TryStreamExt;
|
||||
use mito_codec::row_converter::DensePrimaryKeyCodec;
|
||||
use mito2::memtable::bulk::context::BulkIterContext;
|
||||
use mito2::memtable::bulk::part::{BulkPartConverter, BulkPartEncoder};
|
||||
use mito2::memtable::bulk::part_reader::EncodedBulkPartIter;
|
||||
use mito2::memtable::bulk::part_reader::ParquetBulkPartIter;
|
||||
use mito2::read::range_cache::bench_cache_flat_range_stream;
|
||||
use mito2::sst::parquet::DEFAULT_ROW_GROUP_SIZE;
|
||||
use mito2::sst::{FlatSchemaOptions, to_flat_sst_arrow_schema};
|
||||
@@ -68,7 +68,10 @@ fn cache_flat_range_stream_bench(c: &mut Criterion) {
|
||||
let encoded_part = encoder.encode_part(&bulk_part).unwrap().unwrap();
|
||||
|
||||
// Decode all record batches
|
||||
let num_row_groups = encoded_part.metadata().parquet_metadata.num_row_groups();
|
||||
let num_row_groups = encoded_part
|
||||
.parquet_metadata()
|
||||
.expect("benchmark uses Parquet")
|
||||
.num_row_groups();
|
||||
let context = Arc::new(
|
||||
BulkIterContext::new(
|
||||
metadata.clone(),
|
||||
@@ -89,8 +92,9 @@ fn cache_flat_range_stream_bench(c: &mut Criterion) {
|
||||
group.bench_function("baseline_iter_stream", |b| {
|
||||
b.iter(|| {
|
||||
rt.block_on(async {
|
||||
let iter = EncodedBulkPartIter::try_new(
|
||||
&encoded_part,
|
||||
let iter = ParquetBulkPartIter::try_new(
|
||||
encoded_part.parquet_part().unwrap(),
|
||||
encoded_part.metadata().num_series as usize,
|
||||
context.clone(),
|
||||
row_groups.clone(),
|
||||
None,
|
||||
@@ -108,8 +112,9 @@ fn cache_flat_range_stream_bench(c: &mut Criterion) {
|
||||
group.bench_function("cache_flat_range_stream", |b| {
|
||||
b.iter(|| {
|
||||
rt.block_on(async {
|
||||
let iter = EncodedBulkPartIter::try_new(
|
||||
&encoded_part,
|
||||
let iter = ParquetBulkPartIter::try_new(
|
||||
encoded_part.parquet_part().unwrap(),
|
||||
encoded_part.metadata().num_series as usize,
|
||||
context.clone(),
|
||||
row_groups.clone(),
|
||||
None,
|
||||
|
||||
@@ -402,6 +402,21 @@ impl AccessLayer {
|
||||
provider.can_merge_inputs &= write_opts.max_file_size.is_none();
|
||||
}
|
||||
let context = context.unwrap_or_default();
|
||||
if request.sst_write_format == FormatType::Narthex {
|
||||
if context.limits.is_some() {
|
||||
return crate::error::UnsupportedOperationSnafu {
|
||||
err_msg: "Narthex table compaction is unsupported",
|
||||
}
|
||||
.fail();
|
||||
}
|
||||
return crate::sst::narthex::write_samples(
|
||||
self,
|
||||
request,
|
||||
context.guard,
|
||||
context.cancellation,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
let limits = context.limits;
|
||||
let guard = context.guard.clone();
|
||||
let cancellation = context.cancellation.clone();
|
||||
@@ -439,12 +454,12 @@ impl AccessLayer {
|
||||
// bypass it.
|
||||
let store = self.object_store.clone();
|
||||
let path_provider = RegionFilePathFactory::new(self.table_dir.clone(), self.path_type);
|
||||
let puffin_factory = if limits.is_some() {
|
||||
self.puffin_manager_factory
|
||||
.clone()
|
||||
.with_write_buffer_size(write_opts.write_buffer_size.as_bytes() as usize)
|
||||
let puffin_factory = self.puffin_manager_factory.clone();
|
||||
#[cfg(feature = "enterprise")]
|
||||
let puffin_factory = if let Some(limits) = limits {
|
||||
puffin_factory.with_upload_limits(limits.upload_limits)
|
||||
} else {
|
||||
self.puffin_manager_factory.clone()
|
||||
puffin_factory
|
||||
};
|
||||
let indexer_builder = IndexerBuilderImpl {
|
||||
index_build_inputs: request.index_build_inputs,
|
||||
@@ -464,7 +479,7 @@ impl AccessLayer {
|
||||
// TODO(yingwen): If we support other non-fs stores without the write cache, then
|
||||
// we may have find a way to check whether we need the cleaner.
|
||||
let cleaner = TempFileCleaner::new(region_id, self.object_store.clone());
|
||||
let mut writer = ParquetWriter::new_with_object_store(
|
||||
let writer = ParquetWriter::new_with_object_store(
|
||||
self.object_store.clone(),
|
||||
request.metadata,
|
||||
request.index_config,
|
||||
@@ -482,6 +497,13 @@ impl AccessLayer {
|
||||
.with_write_guard(guard)
|
||||
.with_cancellation(cancellation)
|
||||
.with_memory_limits(limits);
|
||||
#[cfg(feature = "enterprise")]
|
||||
let writer = if let Some(limits) = limits {
|
||||
writer.with_upload_limits(limits.upload_limits)
|
||||
} else {
|
||||
writer
|
||||
};
|
||||
let mut writer = writer;
|
||||
match request.sst_write_format {
|
||||
FormatType::PrimaryKey => {
|
||||
writer
|
||||
@@ -492,6 +514,12 @@ impl AccessLayer {
|
||||
)
|
||||
.await?
|
||||
}
|
||||
FormatType::Narthex => {
|
||||
return crate::error::UnsupportedOperationSnafu {
|
||||
err_msg: "narthex writer must bypass Parquet cache",
|
||||
}
|
||||
.fail();
|
||||
}
|
||||
FormatType::Flat => {
|
||||
writer
|
||||
.write_all_flat(request.source, override_sequence, write_opts)
|
||||
@@ -649,7 +677,8 @@ impl AccessLayer {
|
||||
}
|
||||
|
||||
let path = entry.path();
|
||||
if !path.ends_with(".parquet") && !path.ends_with(".puffin") {
|
||||
if !path.ends_with(".parquet") && !path.ends_with(".puffin")
|
||||
&& crate::sst::location::parse_narthex_file_id(path).is_none() {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
+24
-16
@@ -16,26 +16,34 @@
|
||||
|
||||
use parquet::file::metadata::ParquetMetaData;
|
||||
|
||||
use crate::sst::parquet::DEFAULT_READ_BATCH_SIZE;
|
||||
use crate::sst::parquet::{DEFAULT_READ_BATCH_SIZE, max_row_value_width};
|
||||
|
||||
/// Approximate decoded bytes to produce in one batch.
|
||||
pub(crate) const TARGET_BATCH_BYTES: usize = 64 * 1024 * 1024;
|
||||
|
||||
/// Returns `(num_rows, uncompressed_bytes)` of the largest row group in a Parquet file, which
|
||||
/// bounds the decoded size of a batch read from it.
|
||||
pub(crate) fn largest_row_group_statistic(metadata: &ParquetMetaData) -> Option<(u64, u64)> {
|
||||
metadata
|
||||
.row_groups()
|
||||
.iter()
|
||||
.map(|row_group| {
|
||||
let uncompressed_bytes = row_group
|
||||
.columns()
|
||||
.iter()
|
||||
.map(|column| column.uncompressed_size() as u64)
|
||||
.sum();
|
||||
(row_group.num_rows() as u64, uncompressed_bytes)
|
||||
})
|
||||
.max_by_key(|(_, uncompressed_bytes)| *uncompressed_bytes)
|
||||
/// Returns `(num_rows, bytes)` estimates of the row groups in a Parquet file: the uncompressed
|
||||
/// size of each row group, and one row of the largest decoded string and binary value bytes per
|
||||
/// row of the file (see [max_row_value_width]). Dictionary encoding can make the uncompressed size
|
||||
/// far smaller than the decoded values.
|
||||
pub(crate) fn row_group_statistics(
|
||||
metadata: &ParquetMetaData,
|
||||
) -> impl Iterator<Item = (u64, u64)> + '_ {
|
||||
let encoded = metadata.row_groups().iter().map(|row_group| {
|
||||
let uncompressed_bytes = row_group
|
||||
.columns()
|
||||
.iter()
|
||||
.map(|column| column.uncompressed_size() as u64)
|
||||
.sum();
|
||||
(row_group.num_rows() as u64, uncompressed_bytes)
|
||||
});
|
||||
let width = max_row_value_width(metadata);
|
||||
encoded.chain((width > 0).then_some((1, width)))
|
||||
}
|
||||
|
||||
/// Returns the statistic of [row_group_statistics] with the widest rows, which bounds the decoded
|
||||
/// size of a batch read from the file.
|
||||
pub(crate) fn widest_row_group_statistic(metadata: &ParquetMetaData) -> Option<(u64, u64)> {
|
||||
row_group_statistics(metadata).max_by_key(|(rows, bytes)| estimate_row_width(*rows, *bytes))
|
||||
}
|
||||
|
||||
/// Estimates a batch size from `(num_rows, estimated_bytes)` pairs.
|
||||
|
||||
Vendored
+4
-69
@@ -21,7 +21,7 @@ use store_api::storage::FileId;
|
||||
|
||||
use crate::cache::{CacheStrategy, ColumnarMetaCache};
|
||||
use crate::error::Result;
|
||||
use crate::metrics::{CACHE_BYTES, CACHE_HIT, CACHE_LOAD, CACHE_MISS};
|
||||
use crate::metrics::{CACHE_BYTES, CACHE_HIT, CACHE_MISS};
|
||||
|
||||
const COLUMNAR_META: &str = "columnar_metadata";
|
||||
|
||||
@@ -67,54 +67,6 @@ impl CacheStrategy {
|
||||
}
|
||||
}
|
||||
|
||||
// Native payload blocks used to share the page-cache budget through the shared
|
||||
// `PageRangeCache`, which main replaced with `ParquetPageCache`. That cache serves
|
||||
// uniform-size blocks fetched through a reader, so it cannot hold these aligned blocks
|
||||
// clipped to the payload area.
|
||||
// TODO(narthex-merge): re-attach native payload byte caching to a dedicated page-cache
|
||||
// budget in `CacheManager`; until then payload reads stay uncached.
|
||||
/// Placeholder for the disabled native payload byte cache.
|
||||
#[allow(dead_code)]
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct PayloadCache {
|
||||
namespace: FileId,
|
||||
}
|
||||
|
||||
impl CacheStrategy {
|
||||
pub(crate) fn columnar_payload(&self, _namespace: FileId) -> Option<PayloadCache> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Placeholder for one cached payload block; lookups always miss.
|
||||
#[allow(dead_code)]
|
||||
pub(crate) struct PayloadPartCache {
|
||||
namespace: FileId,
|
||||
generation: FileId,
|
||||
part: u32,
|
||||
file_size: u64,
|
||||
}
|
||||
|
||||
impl PayloadCache {
|
||||
pub(crate) fn part(&self, generation: FileId, part: u32, file_size: u64) -> PayloadPartCache {
|
||||
PayloadPartCache {
|
||||
namespace: self.namespace,
|
||||
generation,
|
||||
part,
|
||||
file_size,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PayloadPartCache {
|
||||
pub(crate) fn get(&self, _range: &std::ops::Range<u64>) -> Option<bytes::Bytes> {
|
||||
CACHE_MISS.with_label_values(&["columnar_payload"]).inc();
|
||||
None
|
||||
}
|
||||
|
||||
pub(crate) fn insert(&self, _range: &std::ops::Range<u64>, _bytes: &bytes::Bytes) {}
|
||||
}
|
||||
|
||||
/// Loads only validated immutable structures. Identities include the generation path,
|
||||
/// object length, and the complete reference/codec context used to validate the value.
|
||||
/// Oversized entries bypass admission; disabled caches perform the same validation.
|
||||
@@ -143,8 +95,9 @@ pub(crate) async fn load<T: Send + Sync + 'static>(
|
||||
return Ok(value);
|
||||
}
|
||||
CACHE_MISS.with_label_values(&[COLUMNAR_META]).inc();
|
||||
CACHE_LOAD.with_label_values(&[COLUMNAR_META]).inc();
|
||||
let value = Arc::new(loader.await?);
|
||||
static METRICS: std::sync::LazyLock<Arc<common_cache::metrics::CacheMetrics>> =
|
||||
std::sync::LazyLock::new(|| crate::metrics::cache_loading_metrics(COLUMNAR_META));
|
||||
let value = Arc::new(METRICS.loads.observe(loader).await?);
|
||||
// A caller may flush buffered output while its loader is Pending, then stop
|
||||
// polling it under downstream backpressure. Never hold a shared lock across
|
||||
// that await: another stream may need the lock to finish the current series.
|
||||
@@ -180,24 +133,6 @@ mod tests {
|
||||
use crate::cache::CacheManager;
|
||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||
|
||||
// TODO(narthex-merge): restore payload-block assertions once the byte cache gets a budget.
|
||||
#[test]
|
||||
fn payload_cache_stays_disabled_without_a_page_budget() {
|
||||
let manager = Arc::new(CacheManager::builder().page_cache_size(4096).build());
|
||||
let strategy = CacheStrategy::EnableAll(manager);
|
||||
assert!(strategy.columnar_payload(FileId::random()).is_none());
|
||||
assert!(
|
||||
CacheStrategy::EnableAll(Arc::new(CacheManager::default()))
|
||||
.columnar_payload(FileId::random())
|
||||
.is_none()
|
||||
);
|
||||
assert!(
|
||||
CacheStrategy::Disabled
|
||||
.columnar_payload(FileId::random())
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[rstest::rstest]
|
||||
#[case::same_key(false)]
|
||||
#[case::stripe_collision(true)]
|
||||
|
||||
Vendored
+6
@@ -344,6 +344,12 @@ impl WriteCache {
|
||||
)
|
||||
.await?
|
||||
}
|
||||
crate::sst::FormatType::Narthex => {
|
||||
return crate::error::UnsupportedOperationSnafu {
|
||||
err_msg: "narthex writer bypasses Parquet write cache",
|
||||
}
|
||||
.fail();
|
||||
}
|
||||
crate::sst::FormatType::Flat => {
|
||||
writer
|
||||
.write_all_flat(write_request.source, override_sequence, write_opts)
|
||||
|
||||
@@ -22,6 +22,8 @@ pub mod multi_region;
|
||||
mod overlap;
|
||||
pub mod picker;
|
||||
mod reader;
|
||||
#[cfg(test)]
|
||||
pub(crate) use reader::CompactionSstReaderBuilder;
|
||||
pub mod run;
|
||||
mod scheduler;
|
||||
mod task;
|
||||
@@ -41,11 +43,11 @@ use common_time::range::TimestampRange;
|
||||
pub(crate) use json2::{
|
||||
Json2RewritePlans, collect_json2_rewrite_plans, rewrite_json2_batch, rewrite_json2_schema,
|
||||
};
|
||||
pub use scheduler::CompactionRequest;
|
||||
pub(crate) use scheduler::{
|
||||
CancelCompactionResult, CompactionCoordinator, CompactionExecution, CompactionPickFinished,
|
||||
CompactionScheduler, CompactionState, CompactionStateRef, CompactionTransition,
|
||||
};
|
||||
pub use scheduler::{CompactionGuard, CompactionRequest};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use snafu::ResultExt;
|
||||
use store_api::mito_engine_options::{TWCS_ACTIVE_WINDOW_TRIGGER_FILE_NUM, TWCS_TRIGGER_FILE_NUM};
|
||||
|
||||
@@ -318,6 +318,8 @@ impl CompactionRegionOpener {
|
||||
};
|
||||
|
||||
let manifest = manifest_manager.manifest();
|
||||
let mut region_options = req.region_options.clone();
|
||||
crate::region::opener::sanitize_region_options(&manifest, &mut region_options);
|
||||
let region_metadata = manifest.metadata.clone();
|
||||
let hook: Option<RegionHookRef> = req.plugins.get();
|
||||
let manifest_ctx = Arc::new(ManifestContext::new(
|
||||
@@ -341,7 +343,7 @@ impl CompactionRegionOpener {
|
||||
ssts.add_files(file_purger.clone(), manifest.files.values().cloned());
|
||||
CompactionVersion {
|
||||
metadata: region_metadata.clone(),
|
||||
options: req.region_options.clone(),
|
||||
options: region_options.clone(),
|
||||
ssts: Arc::new(ssts),
|
||||
// Remote execution uses an already picked output. A manifest-only
|
||||
// opener cannot prove that a new LastNonNull pick is memtable-safe.
|
||||
@@ -355,26 +357,23 @@ impl CompactionRegionOpener {
|
||||
Either::Left(ttl) => ttl,
|
||||
// Get the ttl from the schema metadata manager.
|
||||
Either::Right(schema_metadata_manager) => {
|
||||
let (_, ttl) = find_dynamic_options(
|
||||
req.region_id,
|
||||
&req.region_options,
|
||||
&schema_metadata_manager,
|
||||
)
|
||||
.await
|
||||
.unwrap_or_else(|e| {
|
||||
warn!(e; "Failed to get ttl for region: {}", region_metadata.region_id);
|
||||
(
|
||||
crate::region::options::CompactionOptions::default(),
|
||||
TimeToLive::default(),
|
||||
)
|
||||
});
|
||||
let (_, ttl) =
|
||||
find_dynamic_options(req.region_id, ®ion_options, &schema_metadata_manager)
|
||||
.await
|
||||
.unwrap_or_else(|e| {
|
||||
warn!(e; "Failed to get ttl for region: {}", region_metadata.region_id);
|
||||
(
|
||||
crate::region::options::CompactionOptions::default(),
|
||||
TimeToLive::default(),
|
||||
)
|
||||
});
|
||||
ttl
|
||||
}
|
||||
};
|
||||
|
||||
Ok(CompactionRegion {
|
||||
region_id: req.region_id,
|
||||
region_options: req.region_options.clone(),
|
||||
region_options: region_options.clone(),
|
||||
engine_config: self.mito_config.clone(),
|
||||
region_metadata: region_metadata.clone(),
|
||||
// Lets the scan reuse the input footers read while planning the merge.
|
||||
@@ -397,6 +396,16 @@ impl CompactionRegionOpener {
|
||||
}
|
||||
|
||||
impl CompactionRegion {
|
||||
/// Estimates the memory admission reserves for merging `unit`, with the read parallelism and
|
||||
/// merge mode the merge uses.
|
||||
pub(crate) fn estimated_memory_bytes(&self, unit: &CompactionUnit) -> u64 {
|
||||
let options = &self.current_version.options;
|
||||
unit.estimated_memory_bytes(
|
||||
compaction_output_parallelism(&self.region_options, &self.engine_config),
|
||||
!options.append_mode && options.merge_mode() == MergeMode::LastNonNull,
|
||||
)
|
||||
}
|
||||
|
||||
/// Get the file purger of the compaction region.
|
||||
pub fn file_purger(&self) -> Option<Arc<LocalFilePurger>> {
|
||||
self.file_purger.clone()
|
||||
@@ -564,9 +573,10 @@ impl CompactionContext {
|
||||
/// Remote compaction runs off-process and ships `MergeOutput` over the wire;
|
||||
/// [`MergeOutput::sst_infos`] is `#[serde(skip)]` because the parquet footer
|
||||
/// (`ParquetMetaData`) is not serde-serializable. To avoid feeding the hook
|
||||
/// default (zero) values for real SSTs, this rebuilds the seven fields `FileMeta`
|
||||
/// default (zero) values for real SSTs, this rebuilds the eight fields `FileMeta`
|
||||
/// and `SstInfo` share: `file_id`, `time_range`, `file_size`,
|
||||
/// `max_row_group_uncompressed_size`, `num_rows`, `num_row_groups`, `num_series`.
|
||||
/// `max_row_group_uncompressed_size`, `max_row_group_decoded_size`, `num_rows`,
|
||||
/// `num_row_groups`, `num_series`.
|
||||
///
|
||||
/// Two fields stay default and **cannot be recovered on the datanode**:
|
||||
/// - `file_metadata` — the parquet footer, whose column min/max/null-count
|
||||
@@ -586,6 +596,7 @@ fn sst_info_from_file_meta(meta: &FileMeta) -> SstInfo {
|
||||
time_range: meta.time_range,
|
||||
file_size: meta.file_size,
|
||||
max_row_group_uncompressed_size: meta.max_row_group_uncompressed_size,
|
||||
max_row_group_decoded_size: meta.max_row_group_decoded_size,
|
||||
num_rows: meta.num_rows as usize,
|
||||
num_row_groups: meta.num_row_groups,
|
||||
num_series: meta.num_series,
|
||||
@@ -594,6 +605,16 @@ fn sst_info_from_file_meta(meta: &FileMeta) -> SstInfo {
|
||||
}
|
||||
}
|
||||
|
||||
/// Parallelism of encoding an output, which is also the parallelism of reading its inputs.
|
||||
/// Admission sizes the read-ahead with it, so every caller must use this function.
|
||||
pub(crate) fn compaction_output_parallelism(
|
||||
region_options: &RegionOptions,
|
||||
engine_config: &MitoConfig,
|
||||
) -> usize {
|
||||
region_options
|
||||
.compaction_output_parallelism_or(engine_config.experimental_compaction_output_parallelism)
|
||||
}
|
||||
|
||||
/// `[MergeOutput]` represents the output of merging SST files.
|
||||
#[derive(Default, Debug, Serialize, Deserialize)]
|
||||
pub struct MergeOutput {
|
||||
@@ -790,6 +811,7 @@ impl DefaultSstMerger {
|
||||
.join(",");
|
||||
let sequence_metadata = output_sequence_metadata(&context, &output.inputs);
|
||||
let builder = CompactionSstReaderBuilder {
|
||||
narthex_format: context.region_options.sst_format == Some(FormatType::Narthex),
|
||||
metadata: context.region_metadata.clone(),
|
||||
sst_layer: context.access_layer.clone(),
|
||||
cache: context.cache_manager.clone(),
|
||||
@@ -836,10 +858,14 @@ impl DefaultSstMerger {
|
||||
.with_puffin_metadata_cache(context.cache_manager.puffin_metadata_cache().cloned()),
|
||||
can_merge_inputs,
|
||||
});
|
||||
let source = tokio::select! {
|
||||
let (source, row_group_size) = tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.cancelled() => return error::CompactionCancelledSnafu.fail(),
|
||||
source = builder.build_flat_sst_reader() => source?,
|
||||
source = builder.build_flat_sst_reader_and_row_group_size(write_opts.row_group_size) => source?,
|
||||
};
|
||||
let write_opts = WriteOptions {
|
||||
row_group_size,
|
||||
..write_opts
|
||||
};
|
||||
let source = spawn_merge(source);
|
||||
|
||||
@@ -858,7 +884,11 @@ impl DefaultSstMerger {
|
||||
// their effective sequences here could promote old rows above
|
||||
// versions in SSTs that were not part of this merge.
|
||||
max_sequence: None,
|
||||
sst_write_format: if flat_format {
|
||||
sst_write_format: if context.region_options.sst_format
|
||||
== Some(FormatType::Narthex)
|
||||
{
|
||||
FormatType::Narthex
|
||||
} else if flat_format {
|
||||
FormatType::Flat
|
||||
} else {
|
||||
FormatType::PrimaryKey
|
||||
@@ -898,6 +928,7 @@ impl DefaultSstMerger {
|
||||
level: output.output_level,
|
||||
file_size: sst_info.file_size,
|
||||
max_row_group_uncompressed_size: sst_info.max_row_group_uncompressed_size,
|
||||
max_row_group_decoded_size: sst_info.max_row_group_decoded_size,
|
||||
available_indexes: sst_info.index_metadata.build_available_indexes(),
|
||||
indexes: sst_info.index_metadata.build_indexes()?,
|
||||
index_file_size: sst_info.index_metadata.file_size,
|
||||
@@ -995,6 +1026,8 @@ impl<M: SstMerger> DefaultCompactor<M> {
|
||||
compaction_time_window: Some(unit.time_window_size),
|
||||
..Default::default()
|
||||
};
|
||||
// Outputs are merged one at a time; `CompactionUnit::estimated_memory_bytes` reserves
|
||||
// only the largest output.
|
||||
for output in &unit.outputs {
|
||||
if self.cancel_token.is_cancelled() {
|
||||
return error::CompactionCancelledSnafu.fail();
|
||||
@@ -1009,15 +1042,13 @@ impl<M: SstMerger> DefaultCompactor<M> {
|
||||
WriteOptions {
|
||||
write_buffer_size: context.engine_config.sst_write_buffer_size,
|
||||
max_file_size: unit.max_file_size,
|
||||
// Narrowed by the decoded sizes of the inputs once their footers are read.
|
||||
row_group_size: context.region_options.row_group_size(),
|
||||
float_field_encoding: context.region_options.float_field_encoding,
|
||||
encode_parallelism: context
|
||||
.region_options
|
||||
.compaction_output_parallelism_or(
|
||||
context
|
||||
.engine_config
|
||||
.experimental_compaction_output_parallelism,
|
||||
),
|
||||
encode_parallelism: compaction_output_parallelism(
|
||||
&context.region_options,
|
||||
&context.engine_config,
|
||||
),
|
||||
encode_runtime: EncodeRuntime::Compact,
|
||||
},
|
||||
self.cancel_token.clone(),
|
||||
@@ -1089,15 +1120,13 @@ where
|
||||
let write_opts = WriteOptions {
|
||||
write_buffer_size: compaction_region.engine_config.sst_write_buffer_size,
|
||||
max_file_size: picker_output.max_file_size,
|
||||
// Narrowed by the decoded sizes of the inputs once their footers are read.
|
||||
row_group_size: compaction_region.region_options.row_group_size(),
|
||||
float_field_encoding: compaction_region.region_options.float_field_encoding,
|
||||
encode_parallelism: compaction_region
|
||||
.region_options
|
||||
.compaction_output_parallelism_or(
|
||||
compaction_region
|
||||
.engine_config
|
||||
.experimental_compaction_output_parallelism,
|
||||
),
|
||||
encode_parallelism: compaction_output_parallelism(
|
||||
&compaction_region.region_options,
|
||||
&compaction_region.engine_config,
|
||||
),
|
||||
encode_runtime: EncodeRuntime::Compact,
|
||||
};
|
||||
let merger = self.merger.clone();
|
||||
@@ -1903,6 +1932,7 @@ mod tests {
|
||||
deletes.clone()
|
||||
});
|
||||
let mut reader = CompactionSstReaderBuilder {
|
||||
narthex_format: false,
|
||||
metadata: compaction_region.region_metadata.clone(),
|
||||
sst_layer: region.access_layer.clone(),
|
||||
cache: engine.cache_manager(),
|
||||
@@ -2024,6 +2054,7 @@ mod tests {
|
||||
assert_eq!(1, files.len());
|
||||
let outputs: Vec<_> = files.into_iter().map(new_file_handle).collect();
|
||||
let mut reader = CompactionSstReaderBuilder {
|
||||
narthex_format: false,
|
||||
metadata: version.metadata.clone(),
|
||||
sst_layer: region.access_layer.clone(),
|
||||
cache: Arc::new(CacheManager::default()),
|
||||
|
||||
@@ -64,10 +64,10 @@ pub struct MultiRegionCompactionPlan {
|
||||
pub sources: Vec<FileMeta>,
|
||||
/// Metadata and routing must belong to the same physical-table snapshot.
|
||||
pub targets: BTreeMap<RegionId, MultiRegionTarget>,
|
||||
/// Working-set admission budget, including all resident writers and their finish workspace.
|
||||
/// This bounds managed buffers and estimates codec/index allocations, not process RSS.
|
||||
/// It must be large enough that the per-buffer share still covers the storage
|
||||
/// multipart minimum, otherwise the plan is rejected before any output.
|
||||
/// Total working-set admission budget for computation and all resident uploads.
|
||||
/// Upload chunks follow the destination backend's limits independently of the Arrow
|
||||
/// batch limit. The executor reserves uploads before sizing the compute buffers and
|
||||
/// checks the estimated working set before creating outputs. This is not a process RSS limit.
|
||||
pub memory_limit: usize,
|
||||
/// Soft size limit, in bytes, of one output SST. A file rolls over at the next
|
||||
/// series boundary after it is exceeded, so a single series may stay in one file.
|
||||
@@ -99,7 +99,7 @@ pub struct MultiRegionCompactionStats {
|
||||
pub source_store_page_bytes: u64,
|
||||
pub output_rows: u64,
|
||||
pub output_bytes: u64,
|
||||
/// Conservative admission estimate, including reader pages, writers, indexes and finish.
|
||||
/// Admission estimate for reader pages, encoders, indexes, uploads, and finish workspace.
|
||||
pub estimated_memory_bytes: u64,
|
||||
/// Peak retained equal-key group storage (including shared buffer capacities).
|
||||
pub peak_group_bytes: u64,
|
||||
@@ -160,6 +160,14 @@ pub async fn compact_regions(
|
||||
}
|
||||
|
||||
fn validate_plan(plan: &MultiRegionCompactionPlan) -> Result<RegionMetadataRef> {
|
||||
ensure!(
|
||||
plan.targets
|
||||
.values()
|
||||
.all(|target| target.options.sst_format != Some(crate::sst::FormatType::Narthex)),
|
||||
InvalidMultiRegionCompactionSnafu {
|
||||
reason: "Table compaction does not support Narthex storage"
|
||||
}
|
||||
);
|
||||
ensure!(
|
||||
!plan.sources.is_empty(),
|
||||
InvalidMultiRegionCompactionSnafu {
|
||||
|
||||
@@ -15,16 +15,18 @@ use api::v1::SemanticType;
|
||||
use datatypes::arrow::datatypes::SchemaRef;
|
||||
use datatypes::schema::{ColumnEncoding, FulltextBackend};
|
||||
use index::fulltext_index::create::TantivyFulltextIndexCreator;
|
||||
use object_store::ObjectStore;
|
||||
use parquet::arrow::ArrowSchemaConverter;
|
||||
use parquet::file::metadata::ParquetMetaData;
|
||||
use snafu::{ResultExt, ensure};
|
||||
use snafu::{OptionExt, ResultExt, ensure};
|
||||
|
||||
use crate::compaction::multi_region::{
|
||||
MultiRegionCompactionContext, MultiRegionCompactionPlan, MultiRegionTarget,
|
||||
};
|
||||
use crate::compaction::multi_region::{MultiRegionCompactionPlan, MultiRegionTarget};
|
||||
use crate::config::{FulltextIndexConfig, MitoConfig};
|
||||
use crate::error::{IndexOptionsSnafu, MultiRegionCompactionResourceSnafu, Result};
|
||||
use crate::sst::DEFAULT_WRITE_BUFFER_SIZE;
|
||||
use crate::sst::parquet::max_row_group_value_bytes;
|
||||
use crate::sst::parquet::writer::SstWriteLimits;
|
||||
use crate::sst::upload::buffered::UploadLimits;
|
||||
|
||||
pub(crate) const BATCH_SIZE: usize = 64;
|
||||
/// Cap on the rows of one output row group.
|
||||
@@ -40,9 +42,11 @@ pub(crate) const MAX_ROW_GROUP_SIZE: usize = 1024;
|
||||
/// separate runtime checks. Neither estimate nor buffer accounting measures RSS.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct MemoryLimits {
|
||||
pub(crate) batch: usize,
|
||||
pub(crate) arrow_batch_bytes: usize,
|
||||
pub(crate) group: usize,
|
||||
pub(crate) index: usize,
|
||||
upload_reserved_bytes: usize,
|
||||
compute_budget: usize,
|
||||
/// Reuses index allocation only when the optional working set fits admission.
|
||||
pub(crate) extension_index_memory_limit: Option<usize>,
|
||||
pub(crate) writer: SstWriteLimits,
|
||||
@@ -50,27 +54,46 @@ pub(crate) struct MemoryLimits {
|
||||
}
|
||||
|
||||
impl MemoryLimits {
|
||||
pub(crate) fn new(plan: &MultiRegionCompactionPlan, schema: &SchemaRef) -> Result<Self> {
|
||||
pub(crate) fn new(
|
||||
plan: &MultiRegionCompactionPlan,
|
||||
schema: &SchemaRef,
|
||||
upload: UploadBudget,
|
||||
) -> Result<Self> {
|
||||
let schema = crate::sst::maybe_wrap_schema(schema)?;
|
||||
let columns = ArrowSchemaConverter::new()
|
||||
.convert(&schema)
|
||||
.context(crate::error::WriteParquetSnafu)?
|
||||
.num_columns();
|
||||
let batch =
|
||||
plan.memory_limit / (64 * (plan.sources.len() + plan.targets.len() + BATCH_SIZE + 4));
|
||||
let targets = plan.targets.len();
|
||||
let batch_share = 64usize.saturating_mul(
|
||||
plan.sources
|
||||
.len()
|
||||
.saturating_add(targets)
|
||||
.saturating_add(BATCH_SIZE + 4),
|
||||
);
|
||||
let arrow_batch_bytes = upload.compute_bytes / batch_share;
|
||||
ensure!(
|
||||
arrow_batch_bytes > 0,
|
||||
MultiRegionCompactionResourceSnafu {
|
||||
reason: "No Arrow batch budget after reserving upload memory",
|
||||
}
|
||||
);
|
||||
Ok(Self {
|
||||
batch,
|
||||
group: plan.memory_limit / 16,
|
||||
index: plan.memory_limit / (64 * plan.targets.len()),
|
||||
arrow_batch_bytes,
|
||||
group: upload.compute_bytes / 16,
|
||||
index: upload.compute_bytes / targets / 64,
|
||||
upload_reserved_bytes: upload.reserved_bytes,
|
||||
compute_budget: upload.compute_bytes,
|
||||
extension_index_memory_limit: None,
|
||||
writer: SstWriteLimits {
|
||||
// Parquet 59 preallocates a 1 MiB bit writer for each of the
|
||||
// timestamp/sequence delta encoders. Dictionary interner tables
|
||||
// also have a nonzero minimum, independent of batch row count.
|
||||
working_bytes: 2 * 1024 * 1024
|
||||
+ columns * 128 * 1024
|
||||
+ batch * (MAX_ROW_GROUP_SIZE / BATCH_SIZE),
|
||||
metadata_bytes: plan.memory_limit / (8 * plan.targets.len()),
|
||||
working_bytes: (2usize << 20)
|
||||
.saturating_add(columns.saturating_mul(128 << 10))
|
||||
.saturating_add(arrow_batch_bytes * (MAX_ROW_GROUP_SIZE / BATCH_SIZE)),
|
||||
metadata_bytes: upload.compute_bytes / targets / 8,
|
||||
upload_limits: upload.limits,
|
||||
},
|
||||
estimated: 0,
|
||||
})
|
||||
@@ -79,60 +102,67 @@ impl MemoryLimits {
|
||||
pub(crate) fn admit(
|
||||
&mut self,
|
||||
plan: &MultiRegionCompactionPlan,
|
||||
context: &MultiRegionCompactionContext,
|
||||
config: &MitoConfig,
|
||||
footers: &[Arc<ParquetMetaData>],
|
||||
extension_targets: usize,
|
||||
) -> Result<()> {
|
||||
self.check_upload_minimum(context)?;
|
||||
let mut extra_delta = 0;
|
||||
for target in plan.targets.values() {
|
||||
extra_delta = extra_delta.max(extra_delta_encoder_bytes(target)?);
|
||||
}
|
||||
self.writer.working_bytes = self.writer.working_bytes.saturating_add(extra_delta);
|
||||
// Merge assembly can retain exhausted batches until an output batch is full.
|
||||
let mut bytes = 4_u64
|
||||
.saturating_mul((plan.sources.len() + BATCH_SIZE + 2) as u64)
|
||||
.saturating_mul(self.batch as u64)
|
||||
.saturating_add(6 * self.group as u64);
|
||||
for footer in footers {
|
||||
bytes = bytes.saturating_add(reader_bytes(footer));
|
||||
}
|
||||
for target in plan.targets.values() {
|
||||
bytes = bytes.saturating_add(self.target_bytes(target, &context.config)?);
|
||||
}
|
||||
let estimate = self.estimate_compute_bytes(plan, config, footers)?;
|
||||
let upload = self.writer.upload_limits;
|
||||
ensure!(
|
||||
bytes <= plan.memory_limit as u64,
|
||||
estimate <= self.compute_budget as u64,
|
||||
MultiRegionCompactionResourceSnafu {
|
||||
reason: format!(
|
||||
"Reader/writer/index minimum working set needs {bytes} bytes, budget is {}",
|
||||
plan.memory_limit
|
||||
"Reader/writer/index minimum working set needs {estimate} bytes, compute budget is {} ({} bytes reserved for {}-byte upload chunks out of {} total)",
|
||||
self.compute_budget,
|
||||
self.upload_reserved_bytes,
|
||||
upload.chunk_bytes,
|
||||
plan.memory_limit,
|
||||
),
|
||||
}
|
||||
);
|
||||
// Optional indexes must not turn an admitted data compaction into a
|
||||
// resource failure. Reserve all resident target states together or skip.
|
||||
let admission =
|
||||
admit_extension_indexes(bytes, plan.memory_limit, self.index, extension_targets);
|
||||
admit_extension_indexes(estimate, self.compute_budget, self.index, extension_targets);
|
||||
self.extension_index_memory_limit = admission.limit;
|
||||
self.estimated = admission.estimated;
|
||||
self.estimated = admission.estimated + self.upload_reserved_bytes as u64;
|
||||
common_telemetry::debug!(
|
||||
memory_limit = plan.memory_limit,
|
||||
compute_budget = self.compute_budget,
|
||||
arrow_batch_bytes = self.arrow_batch_bytes,
|
||||
upload_chunk_bytes = upload.chunk_bytes,
|
||||
upload_max_object_bytes = upload.max_object_bytes,
|
||||
upload_reserved_bytes = self.upload_reserved_bytes,
|
||||
estimated_memory_bytes = self.estimated,
|
||||
"Admitted multi-region compaction working set",
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn check_upload_minimum(&self, context: &MultiRegionCompactionContext) -> Result<()> {
|
||||
let minimum = context
|
||||
.access_layer
|
||||
.object_store()
|
||||
.info()
|
||||
.capability()
|
||||
.write_multi_min_size
|
||||
.unwrap_or(0);
|
||||
ensure!(
|
||||
self.batch >= minimum && self.batch > 0,
|
||||
MultiRegionCompactionResourceSnafu {
|
||||
reason: "Storage multipart minimum exceeds the task buffer budget",
|
||||
}
|
||||
);
|
||||
Ok(())
|
||||
/// Estimates the compute working set to compare against the compute budget.
|
||||
fn estimate_compute_bytes(
|
||||
&self,
|
||||
plan: &MultiRegionCompactionPlan,
|
||||
config: &MitoConfig,
|
||||
footers: &[Arc<ParquetMetaData>],
|
||||
) -> Result<u64> {
|
||||
// Merge assembly can retain exhausted batches until an output batch is full.
|
||||
let mut bytes = 4_u64
|
||||
.saturating_mul((plan.sources.len() as u64).saturating_add((BATCH_SIZE + 2) as u64))
|
||||
.saturating_mul(self.arrow_batch_bytes as u64)
|
||||
.saturating_add(6 * self.group as u64);
|
||||
for footer in footers {
|
||||
bytes = bytes.saturating_add(reader_bytes(footer));
|
||||
}
|
||||
for target in plan.targets.values() {
|
||||
bytes = bytes.saturating_add(self.target_bytes(target, config)?);
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
fn target_bytes(&self, target: &MultiRegionTarget, config: &MitoConfig) -> Result<u64> {
|
||||
@@ -142,15 +172,22 @@ impl MemoryLimits {
|
||||
.context(crate::error::InvalidMetadataSnafu)?
|
||||
.len();
|
||||
// Task/channel allocation plus captured schema and input-map copies.
|
||||
let control = 8 * 1024
|
||||
+ 3 * schema_bytes
|
||||
+ 3 * target.inputs.len() * std::mem::size_of::<crate::sst::file::FileMeta>();
|
||||
// Encoding/finish workspace, SST and index multipart buffers, result metadata.
|
||||
let writer = self.writer.working_bytes * 2 + self.batch * 4 + self.writer.metadata_bytes;
|
||||
let control = (8_u64 << 10)
|
||||
.saturating_add((schema_bytes as u64).saturating_mul(3))
|
||||
.saturating_add(
|
||||
(target.inputs.len() as u64)
|
||||
.saturating_mul((3 * std::mem::size_of::<crate::sst::file::FileMeta>()) as u64),
|
||||
);
|
||||
// A routed batch can be queued while the writer encodes another batch.
|
||||
// Finish workspace includes the encoded Parquet block handed to the uploader.
|
||||
let writer = (self.writer.working_bytes as u64)
|
||||
.saturating_mul(RETAINED_AND_FINISH_SCRATCH_FACTOR)
|
||||
.saturating_add(2 * self.arrow_batch_bytes as u64)
|
||||
.saturating_add(self.writer.metadata_bytes as u64);
|
||||
// Creators are instantiated even in async-index mode. Inverted/skipping
|
||||
// thresholds are shared within their indexers, fulltext is per column.
|
||||
Ok((control as u64)
|
||||
.saturating_add(writer as u64)
|
||||
Ok(control
|
||||
.saturating_add(writer)
|
||||
.saturating_add(4 * self.index as u64)
|
||||
.saturating_add(self.fulltext_bytes(target, &config.fulltext_index)?))
|
||||
}
|
||||
@@ -193,6 +230,136 @@ impl MemoryLimits {
|
||||
}
|
||||
}
|
||||
|
||||
/// Each serial upload can retain three parts: local assembly, the OpenDAL chunker,
|
||||
/// and the backend's pending or in-flight part. Both writers can hold parts while
|
||||
/// Puffin finishes, before Parquet closes.
|
||||
const UPLOAD_CHUNKS_PER_TARGET: usize = 6;
|
||||
const LOCAL_CHUNK_BYTES: usize = 256 << 10;
|
||||
const PUFFIN_COPY_BUFFER_BYTES: usize = 8 << 10;
|
||||
/// Estimate for two writers' part receipts and completion requests, per part number.
|
||||
const COMPLETION_BYTES_PER_PART: usize = 512;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct UploadBudget {
|
||||
limits: UploadLimits,
|
||||
reserved_bytes: usize,
|
||||
pub(crate) compute_bytes: usize,
|
||||
}
|
||||
|
||||
struct UploadGeometry {
|
||||
min_part_bytes: usize,
|
||||
max_part_bytes: usize,
|
||||
max_parts: Option<usize>,
|
||||
max_object_bytes: u64,
|
||||
}
|
||||
|
||||
impl UploadBudget {
|
||||
pub(crate) fn new(plan: &MultiRegionCompactionPlan, store: &ObjectStore) -> Result<Self> {
|
||||
let geometry = UploadGeometry::from_store(store)?;
|
||||
let targets = plan.targets.len();
|
||||
let chunk_bytes = geometry.choose_chunk_bytes(plan);
|
||||
let fixed_bytes =
|
||||
PUFFIN_COPY_BUFFER_BYTES + COMPLETION_BYTES_PER_PART * geometry.max_parts.unwrap_or(0);
|
||||
let reserved_bytes = chunk_bytes
|
||||
.checked_mul(UPLOAD_CHUNKS_PER_TARGET)
|
||||
.and_then(|bytes| bytes.checked_add(fixed_bytes))
|
||||
.and_then(|bytes| bytes.checked_mul(targets))
|
||||
.context(MultiRegionCompactionResourceSnafu {
|
||||
reason: "Table compaction upload reservation overflow",
|
||||
})?;
|
||||
let compute_bytes = plan.memory_limit.checked_sub(reserved_bytes).filter(|bytes| *bytes > 0)
|
||||
.with_context(|| MultiRegionCompactionResourceSnafu {
|
||||
reason: format!(
|
||||
"Upload reservation of {reserved_bytes} bytes for {targets} resident targets with {chunk_bytes}-byte chunks leaves no compute budget (task budget is {})",
|
||||
plan.memory_limit,
|
||||
),
|
||||
})?;
|
||||
Ok(Self {
|
||||
limits: geometry.limits(chunk_bytes),
|
||||
reserved_bytes,
|
||||
compute_bytes,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl UploadGeometry {
|
||||
fn from_store(store: &ObjectStore) -> Result<Self> {
|
||||
let store_info = store.info();
|
||||
let scheme = store_info.scheme();
|
||||
let caps = store_info.capability();
|
||||
let (max_parts, protocol_part_max, protocol_object_max) = match scheme {
|
||||
"s3" | "oss" => (Some(10_000), usize::MAX, u64::MAX),
|
||||
// GCS caps even multipart objects at 5 TiB: https://cloud.google.com/storage/quotas#objects
|
||||
"gcs" => (Some(10_000), usize::MAX, 5_u64 << 40),
|
||||
// OpenDAL 0.59 does not advertise Azure's Put Block limit.
|
||||
"azblob" => (Some(50_000), 4000 << 20, u64::MAX),
|
||||
"fs" => (None, usize::MAX, u64::MAX),
|
||||
// Writers that spool a whole object or have their own transfer queues
|
||||
// need different admission rules (e.g. MySQL and HDFS).
|
||||
_ => {
|
||||
return MultiRegionCompactionResourceSnafu {
|
||||
reason: format!(
|
||||
"Cannot bound table compaction uploads for storage backend {scheme}"
|
||||
),
|
||||
}
|
||||
.fail();
|
||||
}
|
||||
};
|
||||
let min_part_bytes = caps.write_multi_min_size.unwrap_or(1).max(1);
|
||||
let max_part_bytes = caps
|
||||
.write_multi_max_size
|
||||
.unwrap_or(protocol_part_max)
|
||||
.min(protocol_part_max);
|
||||
let max_object_bytes = caps
|
||||
.write_total_max_size
|
||||
.map_or(protocol_object_max, |size| {
|
||||
protocol_object_max.min(size as u64)
|
||||
});
|
||||
ensure!(
|
||||
caps.write
|
||||
&& caps.write_can_multi
|
||||
&& min_part_bytes <= max_part_bytes
|
||||
&& max_object_bytes > 0,
|
||||
MultiRegionCompactionResourceSnafu {
|
||||
reason: format!(
|
||||
"No supported upload chunk size for {scheme}: minimum {min_part_bytes}, maximum {max_part_bytes}, object limit {max_object_bytes}"
|
||||
),
|
||||
}
|
||||
);
|
||||
Ok(Self {
|
||||
min_part_bytes,
|
||||
max_part_bytes,
|
||||
max_parts,
|
||||
max_object_bytes,
|
||||
})
|
||||
}
|
||||
|
||||
fn limits(&self, chunk_bytes: usize) -> UploadLimits {
|
||||
let max_object_bytes = self.max_parts.map_or(self.max_object_bytes, |parts| {
|
||||
self.max_object_bytes
|
||||
.min((chunk_bytes as u64).saturating_mul(parts as u64))
|
||||
});
|
||||
UploadLimits {
|
||||
chunk_bytes,
|
||||
max_object_bytes,
|
||||
}
|
||||
}
|
||||
|
||||
fn choose_chunk_bytes(&self, plan: &MultiRegionCompactionPlan) -> usize {
|
||||
let preferred = self.max_parts.map_or(LOCAL_CHUNK_BYTES, |parts| {
|
||||
// Leave room for a final part near the soft rollover target. The
|
||||
// hard upload limit still applies to a long series or large index.
|
||||
(DEFAULT_WRITE_BUFFER_SIZE.as_bytes() as usize)
|
||||
.max(plan.max_output_file_size.div_ceil(parts - 1))
|
||||
});
|
||||
// Prefer to spend at most one eighth of the task on part buffers
|
||||
// unless the backend minimum requires more.
|
||||
preferred
|
||||
.min(plan.memory_limit / plan.targets.len() / 8 / UPLOAD_CHUNKS_PER_TARGET)
|
||||
.clamp(self.min_part_bytes, self.max_part_bytes)
|
||||
}
|
||||
}
|
||||
|
||||
fn extra_delta_encoder_bytes(target: &MultiRegionTarget) -> Result<usize> {
|
||||
let mut bytes = 0;
|
||||
for column in target
|
||||
@@ -215,12 +382,16 @@ fn extra_delta_encoder_bytes(target: &MultiRegionTarget) -> Result<usize> {
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
fn reader_bytes(footer: &ParquetMetaData) -> u64 {
|
||||
pub(super) fn reader_bytes(footer: &ParquetMetaData) -> u64 {
|
||||
// Dictionary-encoded values decode to more than the uncompressed row group size; the footer
|
||||
// records the largest decoded row group of the file.
|
||||
let decoded = max_row_group_value_bytes(footer);
|
||||
let pages = footer
|
||||
.row_groups()
|
||||
.iter()
|
||||
.map(|group| {
|
||||
(group.total_byte_size().max(0) as u64)
|
||||
.max(decoded)
|
||||
.saturating_mul(RETAINED_AND_FINISH_SCRATCH_FACTOR)
|
||||
.saturating_add(group.compressed_size().max(0) as u64)
|
||||
})
|
||||
@@ -265,7 +436,30 @@ fn admit_extension_indexes(
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{ExtensionIndexAdmission, admit_extension_indexes};
|
||||
use object_store::ObjectStore;
|
||||
use object_store::layers::CapabilityOverrideLayer;
|
||||
use object_store::services::Gcs;
|
||||
|
||||
use super::{ExtensionIndexAdmission, UploadGeometry, admit_extension_indexes};
|
||||
|
||||
#[rstest::rstest]
|
||||
#[case::service_limit(1 << 30, None, 5_u64 << 40)]
|
||||
#[case::advertised_limit(1 << 30, Some(2 << 30), 2 << 30)]
|
||||
#[case::part_count_limit(5 << 20, None, 10_000 * (5_u64 << 20))]
|
||||
fn test_gcs_multipart_object_limit(
|
||||
#[case] chunk_bytes: usize,
|
||||
#[case] advertised: Option<usize>,
|
||||
#[case] expected: u64,
|
||||
) {
|
||||
let store = ObjectStore::new(Gcs::default().bucket("test"))
|
||||
.unwrap()
|
||||
.layer(CapabilityOverrideLayer::new(move |mut caps| {
|
||||
caps.write_total_max_size = advertised;
|
||||
caps
|
||||
}));
|
||||
let geometry = UploadGeometry::from_store(&store).unwrap();
|
||||
assert_eq!(expected, geometry.limits(chunk_bytes).max_object_bytes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extension_indexes_do_not_reject_admitted_data() {
|
||||
|
||||
@@ -14,7 +14,6 @@ use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use arrow_schema::extension::EXTENSION_TYPE_METADATA_KEY;
|
||||
use common_base::readable_size::ReadableSize;
|
||||
use common_time::Timestamp;
|
||||
use datatypes::arrow::array::{
|
||||
@@ -32,10 +31,9 @@ use store_api::metadata::RegionMetadataRef;
|
||||
use store_api::storage::RegionId;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::access_layer::AccessLayerRef;
|
||||
use crate::cache::CacheStrategy;
|
||||
use crate::compaction::json2::collect_json2_rewrite_plans_from_parquet;
|
||||
use crate::compaction::multi_region::memory::{BATCH_SIZE, MemoryLimits};
|
||||
use crate::compaction::multi_region::memory::{BATCH_SIZE, MemoryLimits, UploadBudget};
|
||||
use crate::compaction::multi_region::{
|
||||
MultiRegionCompactionContext, MultiRegionCompactionPlan, MultiRegionTarget, SourceCounters,
|
||||
};
|
||||
@@ -44,22 +42,24 @@ use crate::error::{
|
||||
ComputeArrowSnafu, ExternalSnafu, InvalidMultiRegionCompactionSnafu,
|
||||
MultiRegionCompactionResourceSnafu, NewRecordBatchSnafu, Result,
|
||||
};
|
||||
use crate::read::compat::FlatCompatBatch;
|
||||
use crate::read::flat_merge::FlatMergeReader;
|
||||
use crate::read::flat_projection::FlatProjectionMapper;
|
||||
use crate::read::read_columns::ReadColumns;
|
||||
use crate::read::scan_region::ScanInput;
|
||||
use crate::read::{BoxedRecordBatchStream, timestamp_array_to_i64_slice};
|
||||
use crate::sst::file::{FileHandle, FileMeta};
|
||||
use crate::sst::file_purger::NoopFilePurger;
|
||||
use crate::sst::index::IndexBuildType;
|
||||
use crate::sst::index::handler::PlanContext;
|
||||
use crate::sst::index::registry::{IndexBuildPlan, IndexRegistry};
|
||||
use crate::sst::parquet::decoded_input_size;
|
||||
use crate::sst::parquet::file_range::PreFilterMode;
|
||||
use crate::sst::parquet::flat_format::{
|
||||
primary_key_column_index, sequence_column_index, time_index_column_index,
|
||||
};
|
||||
use crate::sst::parquet::format::{PrimaryKeyArray, need_override_sequence};
|
||||
use crate::sst::parquet::reader::{MetadataCacheMetrics, ParquetReader, ReaderMetrics};
|
||||
use crate::sst::parquet::{Json2RewriteTargets, Json2TargetLayout};
|
||||
use crate::sst::parquet::reader::{MetadataCacheMetrics, ReaderMetrics};
|
||||
use crate::sst::parquet::row_group::ParquetFetchMetrics;
|
||||
|
||||
pub(crate) struct SourceEvent {
|
||||
pub(crate) region_id: RegionId,
|
||||
@@ -88,7 +88,7 @@ impl RoutedBatch {
|
||||
let batch = take_record_batch(&self.batch, &indices).context(ComputeArrowSnafu)?;
|
||||
let batch = compact_dictionaries(batch)?;
|
||||
ensure!(
|
||||
batch.get_array_memory_size() <= source.limits.batch,
|
||||
batch.get_array_memory_size() <= source.limits.arrow_batch_bytes,
|
||||
MultiRegionCompactionResourceSnafu {
|
||||
reason: "Routed batch exceeds the task buffer budget"
|
||||
}
|
||||
@@ -99,21 +99,21 @@ impl RoutedBatch {
|
||||
}
|
||||
|
||||
pub(crate) struct SharedSource {
|
||||
layer: AccessLayerRef,
|
||||
cache: CacheStrategy,
|
||||
sources: Vec<FileMeta>,
|
||||
legacy_overrides: Vec<bool>,
|
||||
expected_rows: Vec<i64>,
|
||||
targets: BTreeMap<RegionId, MultiRegionTarget>,
|
||||
metadata: RegionMetadataRef,
|
||||
mapper: FlatProjectionMapper,
|
||||
json2_targets: Json2RewriteTargets,
|
||||
scan_input: ScanInput,
|
||||
routing_codec: Arc<dyn mito_codec::row_converter::PrimaryKeyCodec>,
|
||||
schema: SchemaRef,
|
||||
merge_schema: SchemaRef,
|
||||
partition_rule: PartitionRuleRef,
|
||||
window: (Timestamp, Timestamp),
|
||||
pub(crate) limits: MemoryLimits,
|
||||
pub(crate) index_plans: BTreeMap<RegionId, Arc<IndexBuildPlan>>,
|
||||
/// Rows and decoded bytes of the sources, which size output row groups.
|
||||
pub(crate) input_size: (u64, u64),
|
||||
peak_group_bytes: AtomicU64,
|
||||
cancellation: CancellationToken,
|
||||
stop: CancellationToken,
|
||||
@@ -127,6 +127,7 @@ impl SharedSource {
|
||||
metadata: RegionMetadataRef,
|
||||
counters: Arc<SourceCounters>,
|
||||
) -> Result<Arc<Self>> {
|
||||
let upload = UploadBudget::new(plan, context.access_layer.object_store())?;
|
||||
let mut common = (*metadata).clone();
|
||||
common.set_partition_expr(None);
|
||||
let metadata = Arc::new(common);
|
||||
@@ -157,9 +158,12 @@ impl SharedSource {
|
||||
let footer = sst.parquet_metadata();
|
||||
footer_bytes = footer_bytes.saturating_add(footer.memory_size());
|
||||
ensure!(
|
||||
footer_bytes <= plan.memory_limit / 8,
|
||||
footer_bytes <= upload.compute_bytes / 8,
|
||||
MultiRegionCompactionResourceSnafu {
|
||||
reason: "Source footer metadata exceeds the task budget",
|
||||
reason: format!(
|
||||
"Source footer metadata needs {footer_bytes} bytes, budget after reserving uploads is {}",
|
||||
upload.compute_bytes / 8,
|
||||
),
|
||||
}
|
||||
);
|
||||
footers.push(footer);
|
||||
@@ -172,32 +176,9 @@ impl SharedSource {
|
||||
.iter()
|
||||
.map(|footer| footer.file_metadata().num_rows())
|
||||
.collect();
|
||||
let input_size = decoded_input_size(footers.iter().map(Arc::as_ref));
|
||||
let layouts = collect_json2_rewrite_plans_from_parquet(&metadata, &footers)?;
|
||||
let mut json2 = BTreeMap::new();
|
||||
for (name, layout) in layouts {
|
||||
let column =
|
||||
metadata
|
||||
.column_by_name(&name)
|
||||
.context(InvalidMultiRegionCompactionSnafu {
|
||||
reason: "JSON2 layout names an unknown column",
|
||||
})?;
|
||||
let extension_metadata = column
|
||||
.column_schema
|
||||
.metadata()
|
||||
.get(EXTENSION_TYPE_METADATA_KEY)
|
||||
.cloned()
|
||||
.context(InvalidMultiRegionCompactionSnafu {
|
||||
reason: "JSON2 extension metadata missing",
|
||||
})?;
|
||||
json2.insert(
|
||||
column.column_id,
|
||||
Json2TargetLayout {
|
||||
extension_metadata,
|
||||
target_layout: layout.target_layout,
|
||||
},
|
||||
);
|
||||
}
|
||||
let json2_targets = Arc::new(json2);
|
||||
let json2_targets = crate::compaction::reader::json2_rewrite_targets(&metadata, &layouts)?;
|
||||
let mapper = FlatProjectionMapper::new_with_json2_rewrite_targets(
|
||||
&metadata,
|
||||
(0..metadata.column_metadatas.len()).collect(),
|
||||
@@ -209,8 +190,15 @@ impl SharedSource {
|
||||
),
|
||||
&json2_targets,
|
||||
)?;
|
||||
let schema = mapper.input_arrow_schema(false);
|
||||
let mut limits = MemoryLimits::new(plan, &schema)?;
|
||||
let schema = mapper.input_arrow_schema(true);
|
||||
let scan_input = ScanInput::builder(context.access_layer.clone(), mapper)
|
||||
.with_compaction(true)
|
||||
.with_page_index_policy(PageIndexPolicy::Skip)
|
||||
.with_batch_size(BATCH_SIZE)
|
||||
.with_cache(cache.clone())
|
||||
.with_json2_rewrite_targets(json2_targets.clone())
|
||||
.build();
|
||||
let mut limits = MemoryLimits::new(plan, &schema, upload)?;
|
||||
let mut inverted = context.config.inverted_index.clone();
|
||||
inverted.mem_threshold_on_create =
|
||||
admitted_index_threshold(inverted.mem_threshold_on_create(), limits.index);
|
||||
@@ -240,7 +228,7 @@ impl SharedSource {
|
||||
.collect::<BTreeMap<_, _>>();
|
||||
limits.admit(
|
||||
plan,
|
||||
context,
|
||||
&context.config,
|
||||
&footers,
|
||||
index_plans
|
||||
.values()
|
||||
@@ -262,15 +250,13 @@ impl SharedSource {
|
||||
.collect::<Vec<_>>();
|
||||
let merge_schema = Arc::new(Schema::new(fields));
|
||||
Ok(Arc::new(Self {
|
||||
layer: context.access_layer.clone(),
|
||||
cache,
|
||||
sources: plan.sources.clone(),
|
||||
legacy_overrides,
|
||||
expected_rows,
|
||||
targets: plan.targets.clone(),
|
||||
routing_codec: mito_codec::row_converter::build_primary_key_codec(&metadata),
|
||||
metadata,
|
||||
mapper,
|
||||
json2_targets,
|
||||
scan_input,
|
||||
schema,
|
||||
merge_schema,
|
||||
partition_rule: plan.partition_rule.clone(),
|
||||
@@ -280,6 +266,7 @@ impl SharedSource {
|
||||
),
|
||||
limits,
|
||||
index_plans,
|
||||
input_size,
|
||||
peak_group_bytes: AtomicU64::new(0),
|
||||
cancellation: context.cancellation.clone(),
|
||||
stop: CancellationToken::new(),
|
||||
@@ -357,43 +344,35 @@ impl SharedSource {
|
||||
let mut raw_meta = file.clone();
|
||||
raw_meta.sequence = None;
|
||||
raw_meta.preserve_row_sequence = true;
|
||||
let builder = self
|
||||
.layer
|
||||
.read_sst(FileHandle::new(raw_meta, Arc::new(NoopFilePurger)))
|
||||
.cache(self.cache.clone())
|
||||
.batch_size(BATCH_SIZE)
|
||||
.expected_metadata(Some(self.metadata.clone()))
|
||||
.json2_rewrite_targets(self.json2_targets.clone())
|
||||
.compaction(false)
|
||||
.page_index_policy(PageIndexPolicy::Skip);
|
||||
let handle = FileHandle::new(raw_meta, Arc::new(NoopFilePurger));
|
||||
let input = self.scan_input.prune_file(
|
||||
&handle, PreFilterMode::All, &mut ReaderMetrics::default(),
|
||||
).await?;
|
||||
let mut ranges = smallvec::SmallVec::new();
|
||||
input.build_ranges(-1, &mut ranges);
|
||||
let fetch_metrics = ParquetFetchMetrics::default();
|
||||
let mut rows = 0u64;
|
||||
let input = builder
|
||||
.build_reader_input(&mut ReaderMetrics::default())
|
||||
.await?;
|
||||
if let Some((input, selection)) = input {
|
||||
let compat = FlatCompatBatch::try_new(&self.mapper, input.read_format(), false)?
|
||||
.map(Arc::new);
|
||||
let mut reader = ParquetReader::new(Arc::new(input), selection).await?;
|
||||
let mut last_key = None;
|
||||
while let Some(batch) = reader.next_record_batch().await? {
|
||||
let mut last_key = None;
|
||||
for range in ranges {
|
||||
let Some(mut reader) = range.flat_reader(None, Some(&fetch_metrics)).await? else {
|
||||
continue;
|
||||
};
|
||||
while let Some(batch) = crate::read::scan_util::next_aligned_file_batch(
|
||||
&range, &mut reader, None, false,
|
||||
).await? {
|
||||
self.check_cancelled()?;
|
||||
let preparing = self.clone();
|
||||
let compat = compat.clone();
|
||||
let (batch, previous) = common_runtime::spawn_blocking_compact(move || {
|
||||
preparing.check_cancelled()?;
|
||||
let batch = match compat {
|
||||
Some(compat) => compat.compat(batch)?,
|
||||
None => batch,
|
||||
};
|
||||
let batch = compact_dictionaries(batch)?;
|
||||
let batch_bytes = batch.get_array_memory_size();
|
||||
ensure!(
|
||||
batch_bytes <= preparing.limits.batch,
|
||||
batch_bytes <= preparing.limits.arrow_batch_bytes,
|
||||
MultiRegionCompactionResourceSnafu {
|
||||
reason: format!(
|
||||
"Decoded source batch uses {} bytes, budget is {}",
|
||||
batch_bytes,
|
||||
preparing.limits.batch,
|
||||
preparing.limits.arrow_batch_bytes,
|
||||
),
|
||||
}
|
||||
);
|
||||
@@ -406,10 +385,13 @@ impl SharedSource {
|
||||
self.counters.rows.fetch_add(batch.num_rows() as u64, Ordering::Relaxed);
|
||||
yield batch;
|
||||
}
|
||||
self.counters
|
||||
.store_page_bytes
|
||||
.fetch_add(reader.fetched_store_page_bytes()?, Ordering::Relaxed);
|
||||
}
|
||||
let store_bytes = fetch_metrics.data.lock()
|
||||
.map(|metrics| metrics.page_size_to_fetch_store)
|
||||
.map_err(|_| crate::error::UnexpectedSnafu {
|
||||
reason: "Source fetch metrics lock poisoned",
|
||||
}.build())?;
|
||||
self.counters.store_page_bytes.fetch_add(store_bytes, Ordering::Relaxed);
|
||||
let expected = self.expected_rows[index];
|
||||
if expected < 0 || rows != expected as u64 {
|
||||
Err(InvalidMultiRegionCompactionSnafu {
|
||||
@@ -556,7 +538,61 @@ impl SharedSource {
|
||||
})
|
||||
}
|
||||
|
||||
fn row_owners(&self, batch: &RecordBatch) -> Result<Vec<RegionId>> {
|
||||
/// Materialize only routing dependencies; merge and output retain encoded keys.
|
||||
fn routing_batch(&self, batch: &RecordBatch) -> Result<(RecordBatch, usize)> {
|
||||
let mut materialized_bytes = 0usize;
|
||||
let mut decoded = None;
|
||||
let mut fields = Vec::new();
|
||||
let mut arrays = Vec::new();
|
||||
for name in self.partition_rule.partition_columns() {
|
||||
let column =
|
||||
self.metadata
|
||||
.column_by_name(name)
|
||||
.context(InvalidMultiRegionCompactionSnafu {
|
||||
reason: "Unknown partition column",
|
||||
})?;
|
||||
let array = if let Some(array) = batch.column_by_name(name) {
|
||||
array.clone()
|
||||
} else {
|
||||
if decoded.is_none() {
|
||||
decoded = Some(crate::sst::parquet::flat_format::decode_primary_keys(
|
||||
self.routing_codec.as_ref(),
|
||||
batch,
|
||||
)?);
|
||||
}
|
||||
let array = decoded
|
||||
.as_mut()
|
||||
.context(InvalidMultiRegionCompactionSnafu {
|
||||
reason: "Missing decoded routing key",
|
||||
})?
|
||||
.get_tag_column(column.column_id, None, &column.column_schema.data_type)?;
|
||||
materialized_bytes =
|
||||
materialized_bytes.saturating_add(array.get_array_memory_size());
|
||||
array
|
||||
};
|
||||
fields.push(Field::new(name, array.data_type().clone(), true));
|
||||
arrays.push(array);
|
||||
}
|
||||
let options = datatypes::arrow::record_batch::RecordBatchOptions::new()
|
||||
.with_row_count(Some(batch.num_rows()));
|
||||
let routing =
|
||||
RecordBatch::try_new_with_options(Arc::new(Schema::new(fields)), arrays, &options)
|
||||
.context(NewRecordBatchSnafu)?;
|
||||
Ok((routing, materialized_bytes))
|
||||
}
|
||||
|
||||
pub(super) fn row_owners(&self, batch: &RecordBatch) -> Result<Vec<RegionId>> {
|
||||
let (routing, materialized_bytes) = self.routing_batch(batch)?;
|
||||
ensure!(
|
||||
batch
|
||||
.get_array_memory_size()
|
||||
.saturating_add(materialized_bytes)
|
||||
<= self.limits.arrow_batch_bytes,
|
||||
MultiRegionCompactionResourceSnafu {
|
||||
reason: "Routing projection exceeds the task buffer budget"
|
||||
}
|
||||
);
|
||||
let batch = &routing;
|
||||
let rows = batch.num_rows();
|
||||
let masks = self
|
||||
.partition_rule
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user