Skip to content

fix(kvdb): reject invalid cached records after read failures - #435

Merged
armink merged 3 commits into
armink:masterfrom
xuanlinzhu:fix/kvdb-cached-read-errors
Nov 11, 2026
Merged

armink merged 3 commits into
armink:masterfrom
xuanlinzhu:fix/kvdb-cached-read-errors

Conversation

@xuanlinzhu

@xuanlinzhu xuanlinzhu commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

What this changes

With the KV address cache enabled, find_kv() returned success after read_kv()
failed, so a cached record with a damaged value could still be returned by
fdb_kv_get_obj(). This branch keeps only the cached-record validation part of
the original change and rebuilds the tests on top of it.

  • find_kv() validates a cache hit: the read must succeed, the CRC must match,
    the record must be committed, and its name length must be the requested one.
    An invalid hint is dropped and the lookup falls back to the validated scan.
  • The cache lookup honours a failed read of the stored name instead of using the
    stale hint.
  • read_kv() reports backend failures of the header, CRC data and record name
    reads, and it resets the record metadata before every read, so an iterator
    cannot reuse the length, name length or value address of the previous record
    after a failed read.
  • A maximum-length key stays valid on a cache hit: get_kv_from_cache() already
    compares the raw on-media name, so the lookup no longer compares the copy that
    read_kv() NUL-truncates for such a key.

The successful cache path is unchanged, and neither the public API nor the
storage layout changes. The separate unchecked final value read in get_kv() is
outside this PR. This does not establish the cause of any board-level corruption.

Related issue

Refs #59. This addresses the cached-record lookup portion of the issue, not every
unchecked read in the library.

Test closure

  • Added or updated cases in tests/fdb_kvdb_tc.c or tests/fdb_tsdb_tc.c
  • New cases are registered in the UTEST_UNIT_RUN(...) list of testcase()
  • Cases cover boundaries (sector full / GC triggered / blob crossing write granularity / init check failure)
    • New cases cover a maximum-length key, a value crossing a write unit, stale
      cached entries with and without a replacement, a committed empty blob,
      backend read failures of the cached name, the record header, the CRC data and
      the record name, the name read of the CRC failure branch, and an iterator
      failure after a successful read. Init check failure is outside the changed
      behaviour.
  • Bug fix: the case failed before the fix and passes after, and its name carries the issue number
    • test_fdb_github_issue_59_max_key fails on the initial commit of this PR
      (7 assertions) and passes with the fix.
    • test_fdb_github_issue_59_cached_name_read_error,
      test_fdb_github_issue_59_crc_data_read_error and
      test_fdb_github_issue_59_iterator_read_error fail on the base tree and pass
      with this change.
  • No new case needed, reason: N/A; this changes behaviour and includes new cases.

Seven issue-59 cases run in the normal cached-KVDB test build. No fault injection
hook and no extra configuration macro is needed: the suite runs the KVDB on the
file backend, and shrinking a sector file makes that backend report a short read,
so the first access at or past the new end becomes FDB_READ_ERR. The cases use
that to damage the persisted data, which also covers the file backend read path
itself. The stale-cache case deliberately restores an obsolete cached address;
normal API calls need not create one.

Write granularity covered

  • CI passed for FDB_WRITE_GRAN = 1 / 8 / 32 / 64 / 128 / 256
    • AutoTestCI run on this head passed all six jobs.
  • Local manual verification only, granularities: 1 / 8 / 32 / 64 / 128 / 256
    • Reproduced the CI flow locally with RT-Thread ENV: Arm GNU 10.3, SCons 4.8,
      FlashDBAutoTestBSP, scons --global-macros="FDB_WRITE_GRAN=<n>", then the
      UtestRunner qemu_runner.py under QEMU. KVDB and TSDB pass at all six values,
      and with FDB_USING_READ_CACHE enabled as well.
    • Red runs: with the base tree, the cached-name, CRC-data and iterator cases
      fail; with the initial commit of this PR, the maximum-length-key case fails.
  • Not verified, reason and risk: N/A

Data layout and compatibility

  • KV/TSL node format unchanged
  • Node format changed: version bumped, old data migrates by: N/A
  • Public struct or API in inc/flashdb.h changed, compatibility impact: N/A
  • API or config macro changed, and docs/ plus docs/zh-cn/ are updated: N/A, no runtime API or configuration macro change

Power-loss semantics

  • Not on a write path
    • No write sequence is changed; the existing malformed-header status handling
      remains. The new early exits only stop a read, and read_kv() still writes the
      FDB_KV_ERR_HDR status for a length that cannot be trusted.
  • On a write path, covered by the fdb_xxx_deinit -> fdb_xxx_init reboot simulation: N/A
  • On a write path, not coverable by utest, verification method: N/A

@xuanlinzhu
xuanlinzhu marked this pull request as ready for review November 4, 2026 10:27
@armink
armink requested a balanced review from Copilot November 5, 2026 14:08

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Backend read failures can cause garbage collection to erase valid committed records, and the lookup changes reject otherwise valid maximum-length keys.

3 open issues
What changed in this PR

This PR addresses the cached-record lookup portion of issue #59 by validating KV cache hits and falling back to a scan when cached records are invalid. Public APIs and storage layout remain unchanged.

Changes:

  • Validate cached records against read success, key, CRC, and committed status.
  • Check backend read failures and reset record metadata before reuse.
  • Add registered regression cases for CRC damage, stale cache entries, empty blobs, and lookup after garbage collection.

Official BSP/QEMU execution remains not verified for write granularities 1/8/32/64/128/256.

File Description
tests/​fdb_kvdb_tc.c Adds and registers issue-59 cache-validation regression cases.
src/​fdb_kvdb.c Validates cache hits, evicts invalid entries, and handles record-read failures.

Review effort: Balanced

Comment thread src/fdb_kvdb.c
Comment on lines +402 to +405
if (_fdb_flash_read((fdb_db_t)db, kv->addr.start + KV_HDR_DATA_SIZE + len,
(uint32_t *) buf, FDB_WG_ALIGN(size)) != FDB_NO_ERR) {
return FDB_READ_ERR;
}

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI 多虑了

Comment thread src/fdb_kvdb.c Outdated
if (get_kv_from_cache(db, key, key_len, &kv->addr.start)) {
read_kv(db, kv);
return true;
if (read_kv(db, kv) == FDB_NO_ERR && find_kv_cb(kv, (void *)key, &find_ok)) {

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这点我赞同 AI 的

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

好,我去修改一下。

Comment thread src/fdb_kvdb.c
Comment on lines +369 to +371
if (_fdb_flash_read((fdb_db_t)db, kv->addr.start, (uint32_t *)&kv_hdr,
sizeof(struct kv_hdr_data)) != FDB_NO_ERR) {
return FDB_READ_ERR;

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

没太看懂

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

感觉意思是 遍历上一条记录成功,留下了长度、状态等信息;读取下一条失败时,需要清理这些信息,避免误用上一条的数据。还需要我补充底层返回错误的直接用例。

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Maximum-length keys remain unfindable after transient read failures because fallback lookup compares a NUL-truncated name, requiring a complete on-media comparison with read-success checks and a recovery regression test.

3 open issues
1 previously missed issue

In code that hasn't changed since last review

Medium severity Preserve maximum-length keys after transient read failures

src/​fdb_kvdb.c:652

After a transient read failure evicts a valid FDB_KV_NAME_MAX-byte key, lookups still fail once the backend recovers: find_kv_cb() compares against kv->name, whose last byte read_kv() replaces with NUL. The cached-name eviction at lines 262–264 has the same recovery problem. Make the fallback scan compare the complete on-media name while checking read success, and add a maximum-length-key fault case that verifies recovery after injection is disabled.

Review effort: Balanced

Comment thread .github/workflows/main.yml Outdated
scons --global-macros="FDB_WRITE_GRAN=${{ matrix.write_gran }}" -j$(nproc) -C $TEST_BSP_ROOT
# Enable read-failure injection in this GNU utest build.
printf '\nLFLAGS += " -Wl,--wrap=_fdb_flash_read"\n' >> "$TEST_BSP_ROOT/rtconfig.py"
scons --global-macros="FDB_WRITE_GRAN=${{ matrix.write_gran }},FDB_UTEST_READ_FAULTS" -j$(nproc) -C $TEST_BSP_ROOT

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这里的 CI 脚本能不能不要用动?默认在代码里面就开启 FDB_UTEST_READ_FAULTS 相关测试就好了嘛?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

好的 ,我去修改

@xuanlinzhu
xuanlinzhu force-pushed the fix/kvdb-cached-read-errors branch 3 times, most recently from 04abbcc to e08ed51 Compare November 9, 2026 07:05
@xuanlinzhu

Copy link
Copy Markdown
Contributor Author

这部分CI超时了,感觉是GC的测试用例占用了过多的时间。

ZhuXuanlin and others added 3 commits November 10, 2026 23:25
read_kv() NUL-truncates kv->name when the stored name is exactly
FDB_KV_NAME_MAX bytes, so comparing that copy again after a cache hit rejected
a valid key. get_kv_from_cache() already compared the raw name on the flash, so
reuse that comparison and only validate the record behind the cached address:
read success, CRC, committed status and the exact name length.

Refs armink#59

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
The suite runs the KVDB on the file backend, and shrinking a sector file makes
that backend report a short read: the first access at or past the new end turns
into FDB_READ_ERR. The new cases use that to damage the persisted data and cover
the cached name, record header, CRC data and record name read failures, the
name read of the CRC failure branch, and the iterator metadata reset after a
failed read. No fault injection hook is needed, and no configuration macro or
storage layout changes.

Refs armink#59

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@armink
armink force-pushed the fix/kvdb-cached-read-errors branch from e08ed51 to e54cf36 Compare November 11, 2026 11:27
@armink

armink commented Nov 11, 2026

Copy link
Copy Markdown
Owner

我把这个分支精简后强制推送了,请 git fetch 后 git reset --hard 到新的 head(e54cf36)。

  • 只保留了最初的 7392227(缓存命中时校验记录),去掉了后续的 FDB_UTEST_READ_FAULTS / --wrap=_fdb_flash_read 注入方案、CI workflow 改动,以及 do_gc() 的保护改动,避免测试代码侵入公共头文件。
  • 应用了 review 中关于最大长度 key 的建议:缓存命中时复用 get_kv_from_cache() 已经做过的原始名字比较,不再比较被 read_kv() 截断的 kv->name。
  • 读失败用例改成直接损坏持久化数据:测试跑在文件后端上,截断扇区文件后该后端会返回短读,第一次读到/越过新末尾的读就变成 FDB_READ_ERR,因此不需要任何注入钩子或额外配置宏。
  • 六档 FDB_WRITE_GRAN 的 AutoTestCI 已全部通过,PR 描述也按实际情况更新了。

抱歉打乱了你的分支历史,感谢你的原始修改。

@armink
armink merged commit 360a68d into armink:master Nov 11, 2026
7 checks passed
@xuanlinzhu

xuanlinzhu commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor Author

我把这个分支后强制主动了,请git fetch后git reset --hard到新的头(e54cf36)。

  • 只保留了最初的7392227(缓存命中时校验记录),去掉了后续的FDB_UTEST_READ_FAULTS/--wrap=_fdb_flash_read填充方案、CI工作流程,以及do_gc()保护的内容,避免测试代码入侵公共头文件。
  • 应用了回顾中关于最大长度关键的:缓存命中时恢复get_kv_from_cache()已经建议的原始比较名称,不再比较被read_kv()中断的kv->name。
  • 读取失败示例改成直接损坏持久化数据:测试跑在文件头部上,截断扇区文件后该会返回短读,第一次读到/越过新表单的读取就变成了FDB_READ_ERR,因此不需要任何注入钩子或额外配置宏。
  • 六档FDB_WRITE_GRAN的AutoTestCI已全部通过,PR描述也按实际情况更新了。

抱歉打乱了你的分支历史,感谢你的原始修改。

感谢大佬 主要是我水平不够, 改半天没改好,还需要您帮忙 谢谢

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants