Store v1: Fix two flusher bugs with deletions #114

Merged
vitalif merged 2 commits from koolkhel/vitastor:v1-lost-flush into master 2026-11-23 00:13:11 +03:00
Contributor

Description

Two store v1 flusher bugs. Both happen with immediate_commit=all too.

1. Store v1: Wake up the flusher when journal sectors are written (test_blockstore_chaos --seed 5 --config 12 --steps 30000 --p-delete 30)

  • The flusher puts back entries whose journal sector isn't written yet and stops when nothing else is flushable. Writing the sector moves dirty_start, but nothing woke the flusher, so writes waiting for journal space or for a deletion hung with a full queue of flushable entries.

2. Store v1: Do not queue a deletion for flushing again while it is being flushed (test_blockstore_chaos --seed 60 --config 21 --p-delete 30)

  • A write over a deletion asks for the deletion to be flushed first. If the flusher is already flushing it, that queues the deletion a second time, and the queued entry outlives the deletion. Versions restart from 1 after a deletion, so the stale queued version then names the object's new versions:
    • if it names one that isn't stable yet, the flusher aborts with "BUG: Unexpected dirty_entry ... unstable state during flush";
    • if it's higher than the new stable version, queueing that one is ignored and the write is never flushed. The journal can't be trimmed past it and fills up, and then the store refuses every write with EAGAIN until it restarts.
  • Fix: if the object is being flushed right now (it is in sync_to_repeat), the write raises the repeat version instead, so the flush in progress requeues the object when it finishes, as it already does for versions that come up during a flush.

Changes since the last version (review of 2026-11-22):

  • The --hardened check and find_unflushable_stable() are gone. Commit 2's bug is caught by the existing checks: the same double-queued deletion also aborts with the BUG above, and that is the seed in its subject now. A check that runs once at the end of the test found nothing in 3,600 seeds, because a restart or a crash requeues everything from the journal.
  • Commit order swapped, so that each seed fails right before its commit and passes after it.
  • Rebased onto master 483f5818.

Testing (Ubuntu 24.04, RelWithDebInfo, on 483f5818):

  • --seed 5 --config 12 --steps 30000 --p-delete 30 deadlocks on master and passes with commit 1. --seed 60 --config 21 --p-delete 30 fails on master and with commit 1, and passes with commit 2.
  • Seeds 1-300 on each of the 12 v1 configurations (3,600 runs, --steps 30000 --p-delete 30): 43 fail with commit 1 alone. 36 of them abort with the BUG above, the rest with "big_write journal_entry was allocated over another object", unexpected content after a power outage, checksum mismatches or an assertion in dequeue_read. All 43 pass with commit 2.
  • The whole series fails one of the 3,600: --seed 61 --config 14 --steps 30000 --p-delete 30, a deleted object comes back after a power outage. It passes on master, but it is the journal replay bug listed below, reached through a different flush order: with the replay fixes on top, it passes.
  • test_blockstore_v1 and the default test_blockstore_chaos run pass. Seeds 1-200 with default weights take 109.35 s on master and 109.07 s with the series.

Not included: a deleted object comes back after a clean restart on master too (--seed 1064 --config 12 --steps 30000 --p-delete 30). A follow-up series fixes journal replay. It builds on this one, so it will come as a separate PR once this one is merged.

Contributor Name

Yury Luneff (MIND Software LLC, https://mindsw.io)

CLA

### Description Two store v1 flusher bugs. Both happen with immediate_commit=all too. **1. Store v1: Wake up the flusher when journal sectors are written** (`test_blockstore_chaos --seed 5 --config 12 --steps 30000 --p-delete 30`) - The flusher puts back entries whose journal sector isn't written yet and stops when nothing else is flushable. Writing the sector moves dirty_start, but nothing woke the flusher, so writes waiting for journal space or for a deletion hung with a full queue of flushable entries. **2. Store v1: Do not queue a deletion for flushing again while it is being flushed** (`test_blockstore_chaos --seed 60 --config 21 --p-delete 30`) - A write over a deletion asks for the deletion to be flushed first. If the flusher is already flushing it, that queues the deletion a second time, and the queued entry outlives the deletion. Versions restart from 1 after a deletion, so the stale queued version then names the object's new versions: - if it names one that isn't stable yet, the flusher aborts with "BUG: Unexpected dirty_entry ... unstable state during flush"; - if it's higher than the new stable version, queueing that one is ignored and the write is never flushed. The journal can't be trimmed past it and fills up, and then the store refuses every write with EAGAIN until it restarts. - Fix: if the object is being flushed right now (it is in `sync_to_repeat`), the write raises the repeat version instead, so the flush in progress requeues the object when it finishes, as it already does for versions that come up during a flush. **Changes since the last version** (review of 2026-11-22): - The `--hardened` check and `find_unflushable_stable()` are gone. Commit 2's bug is caught by the existing checks: the same double-queued deletion also aborts with the BUG above, and that is the seed in its subject now. A check that runs once at the end of the test found nothing in 3,600 seeds, because a restart or a crash requeues everything from the journal. - Commit order swapped, so that each seed fails right before its commit and passes after it. - Rebased onto master 483f5818. **Testing** (Ubuntu 24.04, RelWithDebInfo, on 483f5818): - `--seed 5 --config 12 --steps 30000 --p-delete 30` deadlocks on master and passes with commit 1. `--seed 60 --config 21 --p-delete 30` fails on master and with commit 1, and passes with commit 2. - Seeds 1-300 on each of the 12 v1 configurations (3,600 runs, `--steps 30000 --p-delete 30`): 43 fail with commit 1 alone. 36 of them abort with the BUG above, the rest with "big_write journal_entry was allocated over another object", unexpected content after a power outage, checksum mismatches or an assertion in dequeue_read. All 43 pass with commit 2. - The whole series fails one of the 3,600: `--seed 61 --config 14 --steps 30000 --p-delete 30`, a deleted object comes back after a power outage. It passes on master, but it is the journal replay bug listed below, reached through a different flush order: with the replay fixes on top, it passes. - `test_blockstore_v1` and the default `test_blockstore_chaos` run pass. Seeds 1-200 with default weights take 109.35 s on master and 109.07 s with the series. **Not included:** a deleted object comes back after a clean restart on master too (`--seed 1064 --config 12 --steps 30000 --p-delete 30`). A follow-up series fixes journal replay. It builds on this one, so it will come as a separate PR once this one is merged. ### Contributor Name Yury Luneff (MIND Software LLC, https://mindsw.io) ### CLA - [x] I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md
koolkhel added 3 commits 2026-10-27 10:26:39 +03:00
A store v1 stable version that no flush reaches pins the journal for
good, and the store only shows it as writes refused with EAGAIN, which
the test takes for journal pressure. With --hardened, check after every
drain that the newest stable version of every object is being flushed,
or queued under a version that is still in dirty_db and not older than
it. The check scans all of dirty_db, so it is off by default.
The flush queue keeps one version per object, the highest one queued.
A write over a deletion asks for the deletion to be flushed, and if the
flusher is already flushing it, that queues the deletion again. Once the
deletion is gone, the write is renumbered from version 1, and queueing it
is ignored because the queued deletion version is higher. The flusher
then skips the deletion it can't find, the write is never flushed, and
the journal can't be trimmed past it: it fills up and every write fails
with EAGAIN until a restart.

Replace a queued version that is no longer in dirty_db with the one
being queued. Objects that are deleted and rewritten over and over run
into this regularly; ours were the data of an NFS server that reuses
inode numbers.
The flusher puts back the entries whose journal sector isn't written yet
and stops when it finds nothing else to flush. Writing the sector moves
dirty_start and makes them flushable, but nothing woke the flusher then:
when the writes waiting for journal space or for a deletion were the only
thing left, they hung forever, with the queue full of flushable entries
and a trim requested. Happens with immediate_commit=all too.
Owner

Мне тут не нравится вот этот фикс

  1. Store v1: Do not lose the flush of a write over a deletion

The write is renumbered from version 1 once the deletion is gone, and queueing it is ignored because the queued deletion version is higher. The flusher skips the deletion it can't find, so the write is never flushed and the journal can't be trimmed past it.

Сфигали в очередь flush добавляется write одновременно с уже находящимся там delete, если write произошёл ПОВЕРХ этого самого delete, и должен его дождаться? Вот это выглядит как баг и выглядит что именно это править надо, а не просто накрывать проверкой if is_gone.

Мне тут не нравится вот этот фикс >2. Store v1: Do not lose the flush of a write over a deletion >The write is renumbered from version 1 once the deletion is gone, and queueing it is ignored because the queued deletion version is higher. The flusher skips the deletion it can't find, so the write is never flushed and the journal can't be trimmed past it. Сфигали в очередь flush добавляется write одновременно с уже находящимся там delete, если write произошёл ПОВЕРХ этого самого delete, и должен его дождаться? Вот это выглядит как баг и выглядит что именно это править надо, а не просто накрывать проверкой if is_gone.
Owner

Проверил все указанные сиды - они не падают.

Проверил все указанные сиды - они не падают.
Author
Contributor

Опции --hardened на master нет, она добавляется первым коммитом этого PR: 80ef5486 «Check that stable versions get flushed in test_blockstore_chaos --hardened». Без неё сиды ниже ничего не проверяют. Чтобы повторить, нужен этот коммит поверх master (ставится чисто) или просто ветка PR:

git fetch https://git.yourcmc.ru/koolkhel/vitastor.git v1-lost-flush
git cherry-pick 80ef5486

Пять из шести сидов (285, 112, 118 на --config 21, 439 на --config 18 и 19) завязаны на --hardened из первого коммита. Без неё они на master и не должны падать: потерянный flush тогда виден только как EAGAIN, а за 30000 шагов до него не доходит. На master этой опции нет (Unknown option --hardened), а на master + первый коммит они падают так:

test_blockstore_chaos --hardened --seed 285 --config 21 --steps 30000 --p-delete 30
step 2502: 1 stable version(s) will never be flushed: 1:40000 v1

(112 — step 19404, 118 — step 27050, 439 — step 26602). То есть это сиды на то, что ловит проверка: stable-версия, которую flusher уже никогда не сбросит. Считать ли это настоящим багом — решать тебе. У нас из-за этого вставала запись на OSD под нагрузкой, это и было поводом для PR.

Шестой, --seed 5 --config 12 --steps 30000 --p-delete 30, от --hardened не зависит и на текущем master (a7a6d5f3) виснет: stuck: write 1:60000 v4 16384+77824, stuck: write 1:40000 v2 4096+16384. Нужны оба параметра: без --steps 30000 или без --p-delete 30 он проходит.

Опции `--hardened` на master нет, она добавляется первым коммитом этого PR: 80ef5486 «Check that stable versions get flushed in test_blockstore_chaos --hardened». Без неё сиды ниже ничего не проверяют. Чтобы повторить, нужен этот коммит поверх master (ставится чисто) или просто ветка PR: ``` git fetch https://git.yourcmc.ru/koolkhel/vitastor.git v1-lost-flush git cherry-pick 80ef5486 ``` Пять из шести сидов (285, 112, 118 на `--config 21`, 439 на `--config 18` и `19`) завязаны на `--hardened` из первого коммита. Без неё они на master и не должны падать: потерянный flush тогда виден только как EAGAIN, а за 30000 шагов до него не доходит. На master этой опции нет (`Unknown option --hardened`), а на master + первый коммит они падают так: ``` test_blockstore_chaos --hardened --seed 285 --config 21 --steps 30000 --p-delete 30 step 2502: 1 stable version(s) will never be flushed: 1:40000 v1 ``` (112 — step 19404, 118 — step 27050, 439 — step 26602). То есть это сиды на то, что ловит проверка: stable-версия, которую flusher уже никогда не сбросит. Считать ли это настоящим багом — решать тебе. У нас из-за этого вставала запись на OSD под нагрузкой, это и было поводом для PR. Шестой, `--seed 5 --config 12 --steps 30000 --p-delete 30`, от `--hardened` не зависит и на текущем master (a7a6d5f3) виснет: `stuck: write 1:60000 v4 16384+77824`, `stuck: write 1:40000 v2 4096+16384`. Нужны оба параметра: без `--steps 30000` или без `--p-delete 30` он проходит.
koolkhel force-pushed v1-lost-flush from 8ac5cb9510 to 80cd77c09d 2026-11-02 17:18:38 +03:00 Compare
Author
Contributor

Переделал второй коммит, как ты написал, и запушил; ветка заодно перебазирована на текущий master (a7a6d5f3).

Ты прав, баг был именно там. Трассировка --hardened --seed 285 --config 21 по объекту 1:40000:

  • flusher начинает сбрасывать удаление v5;
  • приходит запись поверх удаления (временно v6) и через unshift_stable_flush() ставит в очередь то же удаление v5 второй раз, хотя его уже сбрасывают;
  • flush заканчивается, удаление стёрто, запись перенумерована в v1;
  • enqueue_flush(v1) игнорируется: в flush_versions для объекта висит устаревшая v5, она больше;
  • v5 из очереди пропускается как уже сброшенная, а v1 так и не сбрасывается.

Теперь, если объект сейчас сбрасывается (есть в sync_to_repeat), запись поверх удаления не ставит удаление в очередь заново, а только поднимает версию повтора. После текущего flush объект перепоставится, как для любых версий, пришедших во время flush. is_gone() убран.

Про третий коммит (будить flusher при записи секторов журнала): --seed 5 --config 12 --steps 30000 --p-delete 30 теперь проходит и с одним новым вторым коммитом (порядок flush другой, и до зависания seed не доходит), и на master с одним третьим. Свип seed 1–200 по всем v1-конфигурациям (2400 прогонов, --hardened --steps 30000 --p-delete 30) без третьего коммита зависаний не нашёл. Сама дыра в коде осталась: flusher откладывает записи, чей сектор журнала ещё не записан, и останавливается, а запись сектора его не будит. Поэтому коммит я оставил. Если без отдельного seed не возьмёшь, скажи, уберу его из PR.

Проверено на весь PR: все шесть seed из описания, test_blockstore_v1, test_blockstore_chaos --hardened (200 seed по умолчанию). Описание PR обновил.

Переделал второй коммит, как ты написал, и запушил; ветка заодно перебазирована на текущий master (a7a6d5f3). Ты прав, баг был именно там. Трассировка `--hardened --seed 285 --config 21` по объекту `1:40000`: - flusher начинает сбрасывать удаление v5; - приходит запись поверх удаления (временно v6) и через `unshift_stable_flush()` ставит в очередь то же удаление v5 второй раз, хотя его уже сбрасывают; - flush заканчивается, удаление стёрто, запись перенумерована в v1; - `enqueue_flush(v1)` игнорируется: в `flush_versions` для объекта висит устаревшая v5, она больше; - v5 из очереди пропускается как уже сброшенная, а v1 так и не сбрасывается. Теперь, если объект сейчас сбрасывается (есть в `sync_to_repeat`), запись поверх удаления не ставит удаление в очередь заново, а только поднимает версию повтора. После текущего flush объект перепоставится, как для любых версий, пришедших во время flush. `is_gone()` убран. Про третий коммит (будить flusher при записи секторов журнала): `--seed 5 --config 12 --steps 30000 --p-delete 30` теперь проходит и с одним новым вторым коммитом (порядок flush другой, и до зависания seed не доходит), и на master с одним третьим. Свип seed 1–200 по всем v1-конфигурациям (2400 прогонов, `--hardened --steps 30000 --p-delete 30`) без третьего коммита зависаний не нашёл. Сама дыра в коде осталась: flusher откладывает записи, чей сектор журнала ещё не записан, и останавливается, а запись сектора его не будит. Поэтому коммит я оставил. Если без отдельного seed не возьмёшь, скажи, уберу его из PR. Проверено на весь PR: все шесть seed из описания, `test_blockstore_v1`, `test_blockstore_chaos --hardened` (200 seed по умолчанию). Описание PR обновил.
vitalif requested changes 2026-11-22 15:21:05 +03:00
@@ -1283,6 +1309,9 @@ static const char *help_text =
" --steps <n> Steps per seed (default %ju)\n"
" --config <n> Force configuration <n> instead of deriving it from the seed\n"
" --max-inflight <n> Operations in flight at once (default %u)\n"
" --hardened After every drain, also check the store's internal state, which\n"
Owner
  1. Мне не нравится название hardened, слишком общее, + не понятно: нужна эта проверка? Не нужна? Можно ли как-то упростить проверку так, чтобы она запускалась только на первом сторе, всегда, но не ела дополнительное время, если она действительно нужна? Т.е. можно ли свести проверку к тому, чтобы она запускалась только в конце теста разово? И тогда убрать опцию и проверять всегда (но только v1). Да и вообще: не покрывается ли это уже существующими проверками? Например, разве запись не залипнет, если у нас очередь не двигается?
  2. find_unflushable_stable используется только в тесте? Давайте его тогда пересадим в тест, не надо сам стор закакивать.
1) Мне не нравится название hardened, слишком общее, + не понятно: нужна эта проверка? Не нужна? Можно ли как-то упростить проверку так, чтобы она запускалась только на первом сторе, всегда, но не ела дополнительное время, если она действительно нужна? Т.е. можно ли свести проверку к тому, чтобы она запускалась только в конце теста разово? И тогда убрать опцию и проверять всегда (но только v1). Да и вообще: не покрывается ли это уже существующими проверками? Например, разве запись не залипнет, если у нас очередь не двигается? 2) find_unflushable_stable используется только в тесте? Давайте его тогда пересадим в тест, не надо сам стор закакивать.
koolkhel reviewed 2026-11-22 17:47:44 +03:00
@@ -1283,6 +1309,9 @@ static const char *help_text =
" --steps <n> Steps per seed (default %ju)\n"
" --config <n> Force configuration <n> instead of deriving it from the seed\n"
" --max-inflight <n> Operations in flight at once (default %u)\n"
" --hardened After every drain, also check the store's internal state, which\n"
Author
Contributor

Проверку убрал совсем, вместе с --hardened и find_unflushable_stable(): она не нужна. Подробно:

Залипнет ли запись? Нет. Когда журнал полон, а flusher'у нечего делать (may_advance() == false), v1 не ждёт, а сразу отказывает с EAGAIN (give_up в journal.cpp, проверка места), и тест принимает EAGAIN как нормальное давление журнала. К тому же чистый рестарт или краш перечитывает журнал и заново ставит всё в очередь, так что потерянный flush живёт только до ближайшего рестарта. Поэтому сам потерянный flush существующие проверки не видят.

Проверка разово в конце. Попробовал: в конце теста trim журнала, как у записи, которая ждёт места, и требование, чтобы все stable-версии сбросились. На 3600 сидах (1–300 на каждой из 12 v1-конфигураций, --steps 30000 --p-delete 30) она не сработала ни разу: потеря должна случиться после последнего рестарта или краша, а они идут каждые пару сотен шагов.

Но причина уже покрыта существующими проверками. Тот же двойной enqueue удаления, если устаревшая версия в очереди совпадает с новой нестабильной версией объекта, роняет стор с BUG: Unexpected dirty_entry ... unstable state during flush. На тех же 3600 сидах master + wakeup-коммит падает 43 раза (36 раз этот BUG, остальные — big_write journal_entry was allocated over another object, мусор после power outage, checksum mismatch, assert в dequeue_read), а с исправлением удаления все 43 проходят. Так что у коммита теперь сид на существующие проверки: --seed 60 --config 21 --p-delete 30 — тот самый из «Not included», он лечится этим же коммитом.

Порядок коммитов поменял: сначала wakeup (--seed 5 --config 12 --steps 30000 --p-delete 30 виснет на master и проходит с ним), потом удаление (сид 60 падает на master и на master + wakeup, проходит с ним). Ветка перебазирована на 483f5818, описание PR обновил.

Одно падение из 3600 со всей серией: --seed 61 --config 14 --steps 30000 --p-delete 30, удалённый объект возвращается после power outage. На master он проходит, но это баг replay журнала (как 1064/12), до которого другой порядок flush просто дошёл: со следующей серией (replay) поверх этой он проходит.

Проверку убрал совсем, вместе с `--hardened` и `find_unflushable_stable()`: она не нужна. Подробно: **Залипнет ли запись?** Нет. Когда журнал полон, а flusher'у нечего делать (`may_advance()` == false), v1 не ждёт, а сразу отказывает с EAGAIN (`give_up` в `journal.cpp`, проверка места), и тест принимает EAGAIN как нормальное давление журнала. К тому же чистый рестарт или краш перечитывает журнал и заново ставит всё в очередь, так что потерянный flush живёт только до ближайшего рестарта. Поэтому сам потерянный flush существующие проверки не видят. **Проверка разово в конце.** Попробовал: в конце теста trim журнала, как у записи, которая ждёт места, и требование, чтобы все stable-версии сбросились. На 3600 сидах (1–300 на каждой из 12 v1-конфигураций, `--steps 30000 --p-delete 30`) она не сработала ни разу: потеря должна случиться после последнего рестарта или краша, а они идут каждые пару сотен шагов. **Но причина уже покрыта существующими проверками.** Тот же двойной enqueue удаления, если устаревшая версия в очереди совпадает с новой нестабильной версией объекта, роняет стор с `BUG: Unexpected dirty_entry ... unstable state during flush`. На тех же 3600 сидах master + wakeup-коммит падает 43 раза (36 раз этот BUG, остальные — `big_write journal_entry was allocated over another object`, мусор после power outage, checksum mismatch, assert в `dequeue_read`), а с исправлением удаления все 43 проходят. Так что у коммита теперь сид на существующие проверки: `--seed 60 --config 21 --p-delete 30` — тот самый из «Not included», он лечится этим же коммитом. Порядок коммитов поменял: сначала wakeup (`--seed 5 --config 12 --steps 30000 --p-delete 30` виснет на master и проходит с ним), потом удаление (сид 60 падает на master и на master + wakeup, проходит с ним). Ветка перебазирована на 483f5818, описание PR обновил. Одно падение из 3600 со всей серией: `--seed 61 --config 14 --steps 30000 --p-delete 30`, удалённый объект возвращается после power outage. На master он проходит, но это баг replay журнала (как 1064/12), до которого другой порядок flush просто дошёл: со следующей серией (replay) поверх этой он проходит.
koolkhel changed title from Store v1: Fix two flusher hangs with deletions to Store v1: Fix two flusher bugs with deletions 2026-11-22 17:47:53 +03:00
koolkhel force-pushed v1-lost-flush from 80cd77c09d to 2fe0a864b2 2026-11-22 17:47:55 +03:00 Compare
vitalif merged commit 4ee30fa775 into master 2026-11-23 00:13:11 +03:00
Sign in to join this conversation.
No Reviewers
No Label
2 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: vitalif/vitastor#114
No description provided.