Ditto 应用代码审查与审计
audit
对照最佳实践指南审查使用 Ditto SDK 的应用中的代码或拉取请求(PR):扫描已知的反模式,逐集合检查跨设备时可能失效的假设(锁、唯一性、空结果、订阅覆盖情况),将 schema 变更标记为增量式或破坏性,并按严重程度报告发现的问题及修复建议。用于审查或审计 Ditto 代码、Ditto 应用的拉取请求或差异(diff),或审查发布前的 Ditto 应用。
- License 许可
- MIT
- 最近更新
- 2026-11-13
- Stars
- ★ 0
- Forks
- 0
01 前言 Front Matter
- name
- audit
- description
- Reviews code or a pull request in an app that uses the Ditto SDK against the best practices guide: scans for known anti-patterns, checks per collection the assumptions that fail across devices (locks, uniqueness, empty results, subscription coverage), marks schema changes additive or breaking, and reports findings by severity with fixes. Use to review or audit Ditto code, a pull request or diff of a Ditto app, or a Ditto app before a release.
02 资源文件 4
- 参考文档reference/cross-device-review.md15.3 KB
- 参考文档reference/scanner-rules.md14.1 KB
- 参考文档reference/schema-changes.md10.2 KB
- 脚本scripts/scan.py83.2 KB
03 SKILL.md 正文
Ditto Code Audit
A repeatable review of an app that uses the Ditto SDK 5.2.0 in Flutter, JavaScript, Kotlin, or Swift: a pattern scan, a cross-device review of each collection, and a manual checklist, with the rules in the topic skills. The scan finds what one line shows; assumptions carried over from a single database or a server API show in no single line, and the cross-device review looks for them.
Before You Apply
- Identify the project's SDK and version: Flutter (
ditto_liveinpubspec.yaml/pubspec.lock), JavaScript (@dittolive/dittoinpackage.json), Kotlin (com.ditto:ditto-kotlinin Gradle files), or Swift (DittoSwiftinPackage.swift,Package.resolved, or the Xcode project). The rules target 5.2.0. Note (SDK 5.1.0 and 5.2.0) marks easy-to-miss behavior confirmed on both releases; Note (SDK 5.1.0) marks 5.1.0 behavior that 5.2.0 no longer shows, and Note (SDK 5.2.0) behavior observed on 5.2.0. Issues that only 5.1.0 has are in§ Known Issues in SDK 5.1.0; they apply wherever any device still runs 5.1.0. On a later version, confirm a note (release notes, docs.ditto.live) before reporting it as a defect. If the version cannot be found, apply the 5.2.0 rules, say so in the report, and mark findings that rest on a Note (SDK ...) as version-specific. - In that SDK's page,
${CLAUDE_SKILL_DIR}/../guide/reference/best-practices/platforms/<sdk>.md(flutter,javascript,kotlin,swift), read the Behavior Specific to the <SDK> SDK section at its end, not the whole page (Grep the heading for its line): it lists what only that SDK does.§ Specific to One SDKin the guide's Anti-Pattern Checklist lists the mistakes to look for in that SDK. Open the topic skills'examples/<sdk>/only when you write a fix. § <Heading>cites a section of the full guide: Grep the heading as a fixed string (headings contain(,), and+) inbest-practices/andknowledge/under${CLAUDE_SKILL_DIR}/../guide/reference/, by those names (in the Ditto Cookbook repository they are symbolic links, which a search of their parent does not enter). Ifbest-practices/README.mdis not there, the guide was not installed with the plugin (for example, a checkout without symbolic links): say so in the report, and rank and cite from the topic skills instead.- Read and search files with Read, Glob, and Grep; use the shell only for the scanner,
git, andgh. - Review only; do not change code unless the user asks for fixes. When asked, apply fixes that leave stored data unchanged or change it additively, and ask before a breaking one (step 8).
Workflow
Copy this checklist and work through it:
Ditto audit progress:
- [ ] 1. Scope: paths, a diff, or a snippet (see below); list the files that use Ditto (imports of ditto_live, @dittolive/ditto, DittoSwift, com.ditto)
- [ ] 2. Context: SDK version, platforms, connection mode (Ditto Server or small peers only), and whether the app is deployed or a sample
- [ ] 3. Scan: run scripts/scan.py on the source directories, as a command of its own, even if another shell command was refused
- [ ] 4. Triage: confirm or discard every scanner hit by reading the code around it
- [ ] 5. Inventory: per collection, its subscriptions, reads, writes, and removals, with file:line
- [ ] 6. Cross-device review: ask the eight questions of every collection in the inventory
- [ ] 7. Manual review: walk the table below for the areas the app uses
- [ ] 8. Schema changes: classify each change to stored data, in the code under review and in each fix, as additive or breaking
- [ ] 9. Report: findings by severity, then what was checked and what was not
Do not stop after step 4: a clean scan misses steps 5 to 8.
Step 1: Scope
Decide what is under review from the request or the arguments the skill was invoked with:
- Paths, or nothing: audit those directories, or the whole repository.
- A pull request, a branch, a base ref, or "my changes": read the diff (
gh pr diff <number>,git diff <base>...HEAD, orgit diff HEADfor uncommitted work), and scan only the changed source files (git diff --name-only --diff-filter=d <base>...HEAD). Review the changed lines, but build the inventory in step 5 from the whole repository for every collection that the diff touches: the cross-device questions need every reader and writer, not only the changed ones. Report what the change introduces as findings, and list problems that the unchanged code already had separately and briefly, unless the change makes them worse. Step 8 always applies. - A snippet with no repository: skip steps 3 and 5, ask the eight questions of what the snippet shows, and list what it does not show under what was not checked.
Step 3: Scan
Run it unchained: a permission rule for python3 can allow it when other commands are refused.
python3 ${CLAUDE_SKILL_DIR}/scripts/scan.py lib/ test/
Pass the project's existing source and test directories, such as lib/ test/ (Flutter), src/ (JavaScript), app/src/ (Android), or Sources/ Tests/ (Swift), or for a diff the changed files. (If ${CLAUDE_SKILL_DIR} is not substituted, use this file's directory.) It skips build output, dependencies, and generated files; --exclude GLOB skips more. Exit code 2 means nothing was scanned: fix the paths. Lines marked ditto-scan: ignore[rule] are not reported. The ditto-scan: summary line on stderr means the scan ran, even after warnings such as macOS xcrun cache errors. The script needs only Python 3.8+; without Python, Grep for the patterns in reference/scanner-rules.md.
Every hit is a candidate, not a finding: the scanner cannot tell a test fixture, a deliberate counter-example, or a validated identifier from a defect.
Step 4: Triage
For each hit:
- Read the surrounding function and its callers.
- Check whether the code really breaks the rule: Grep the
§heading that the hit names in the guide and read that section, or the rule of the same name in the skill the hit names (query-sync,data-modeling,storage-lifecycle,transactions-attachments,performance-observability,sdk-setup,testing). - For a hit whose message says it applies to SDK 5.1.0 only (fixed in 5.2.0), such as
delete-evict-use-idsandcomposite-index-mixed-direction, check the version from step 2. If the project uses 5.1.0, or the version is unknown, report it at its severity. If it uses 5.2.0, keep it as a lower-severity note that the code breaks on devices still running 5.1.0 (the code cannot show which releases run in the field), and say so in the finding. - Keep confirmed hits. Report every finding, also from steps 6 and 7, at the severity of its item in
§ Anti-Pattern Checklist(best-practices/anti-patterns.md), which the scanner already uses: Grep a distinctive phrase of the item there instead of reading the page; its severity is the##section above it, or its bold label under§ Specific to One SDK. Where several items match, use the highest. For a finding with no checklist item, use the definitions in step 9 and say that you ranked it yourself. Drop false positives silently unless the pattern is worth a comment (for example a validated key spliced into a backtick identifier).
Steps 5 and 6: Inventory and cross-device review
Read reference/cross-device-review.md and follow it: build the inventory (per collection: subscriptions, reads, writes, removals, and how _id is made, each with file:line and with which devices run it), then ask every question of every collection. The evidence for these defects is in different files, so they are found only by putting the entries side by side.
| # | Question | Typical finding |
|---|---|---|
| 1 | Which devices can write this document, and what does the merge keep? | A value read, changed in code, and written back; a save() that writes every field; a status that devices overwrite |
| 2 | What does a check before a write prove? | A conditional UPDATE or a transaction used as a lock; uniqueness by a local query; COUNT(*) + 1; "never below zero" |
| 3 | What does an empty or small result mean? | Defaults or "not found" from an empty result; execute right after subscribing |
| 4 | Which subscription brings every document that this query reads? | A query, total, or JOIN wider than the subscriptions; a subscription on a field that changes, with stale copies |
| 5 | What does the code assume once a write has returned? | "Sent" after a local write; close or sign-out before the write is confirmed; presence as proof |
| 6 | What if one device removes the document while another edits it, or was offline for weeks? | Husks, data that comes back, a soft-delete filter missing from one query, an _id used again |
| 7 | What happens when this code runs on every device at once? | Defaults without INITIAL DOCUMENTS; cleanup, closing jobs, and migrations on every device; an observer that writes a per-device value or runs a side effect per change |
| 8 | What does the screen show while related documents are on their way? | A forced unwrap of a referenced document; a parent without children; an attachment not yet fetched |
For each candidate, write the shortest sequence of events on two devices that produces the defect. If you cannot, it is not a finding; if the code does not show who writes or how long devices stay offline, report it with that condition stated. Report one finding per root cause, at the line where the fix goes, with the other places it touches under Also:.
Step 7: Manual review
The remaining design and lifecycle problems, by area. Walk the rows for the areas that the app uses; each row is the list to check. Open the named skill only for a row where something looks wrong, and do not report again what step 6 found:
| Area | What to look for | Skill |
|---|---|---|
| Subscriptions | Scoped by stable keys; owned by a long-lived service; registered again every time Ditto opens (also on a cold start that skips login); not re-registered per screen, filter, or search, and not registered twice with one copy left uncancelled; no !=, NOT IN, or clock() in their filters; no personal data as a filter value; relays subscribe to what devices behind them need; soft-deleted documents stay in scope |
query-sync |
| Observers | Registered once per owner, outside render code; released when the owner goes away (Flutter: changes consumed once, stream subscription and observer cancelled in dispose(); Kotlin: close(), or cancelling the coroutine that collects observe); no result objects kept in state; narrow observers per screen region; backpressure for slow work; no counting, logging, or side effect per callback (intermediate states are skipped); no error escaping a callback |
query-sync, performance-observability |
| Data model | Arrays edited by several devices; whole-document rewrites; stored totals; sequential or timestamp-only IDs; consistent type declarations; documents that can grow without bound; counters written by SET, an upsert, or RESTART WITH, or removed with DELETE or UNSET; UNSET of map entries that others edit; own timestamps that decide a winner; timestamps of varying precision; renamed or retyped fields |
data-modeling |
| Deletion | Strategy per collection (DELETE, soft delete, EVICT); offline periods vs tombstone TTL; DELETE not used to free local storage; no WHERE built from optional filters that can end up empty; the flag and deletedAt set together; eviction complementary to subscriptions, at most daily |
storage-lifecycle |
| Transactions | Only the transaction object's execute inside, each awaited; no nesting, including through helper methods; no I/O or dialogs inside; isReadOnly for transactions that only read; an error caught inside is either rolled back or continued on purpose; pending work awaited before closing |
transactions-attachments |
| Attachments | Explicit, lazy, cancellable fetches with a stall timeout; ATTACHMENT declarations; no binaries in documents; a state for a blob that no peer can deliver yet | transactions-attachments |
| Startup and lifecycle | One instance per persistence directory; auth handler set before sync starts, login result checked the SDK's way, no error escaping the handler; system parameters passed in DittoConfig on every open (SDK 5.2+; on 5.1, ALTER SYSTEM after open and before sync starts); no close on background; writes that must reach another device confirmed before closing; transports changed with updateTransportConfig |
sdk-setup |
| Security | No development token or keyless small-peers mode in production; no hardcoded keys; permissions in the webhook based on immutable _id fields; nothing sensitive in peer metadata; users signed out of shared devices as in § Switching users on a shared device |
sdk-setup |
| Indexes and queries | Indexes created at startup for hot filters, sorts, and JOIN keys; no mixed ASC/DESC composite keys while devices run 5.1.0; no functions on indexed fields; ORDER BY with a tie-breaker where order matters |
performance-observability |
| Tests | Local-store tests for DQL statements, soft-delete filters, observer cleanup, and subscription registration | testing |
| SDK-specific behavior | The items for the app's SDK in § Specific to One SDK (for example, Flutter onChange with an unconsumed changes stream, async observer handlers in JavaScript, Kotlin results read after their handler returns, a Swift Ditto instance without a strong reference), and Behavior Specific to the <SDK> SDK on the SDK page |
guide |
| SDK version | Where devices still run 5.1.0: USE IDS in DELETE/EVICT, mixed-direction composite indexes (including ones from ADVISE), ANY ... SATISFIES on several properties, sorted index queries with projections, constants on the left of comparisons; values that Kotlin, Java, Swift, or C# stored incorrectly before 5.2 (§ Known Issues in SDK 5.1.0) |
guide |
The complete severity-ranked list is the guide's § Anti-Pattern Checklist, with the mistakes of each SDK in § Specific to One SDK; the security-specific list is § Security Checklist.
In a sample or demo, a simplification that its README or a code comment states on purpose (for example, one device type assumed per collection) is not a defect of the sample: list each once under "Documented simplifications", with the severity it would have in a deployed app, so that readers who copy the code know what to change.
Step 8: Schema changes
Devices on older app versions keep reading and writing the same documents, so a change to what is stored is a release decision. For a diff, a pull request, or a branch, and for any fix that changes stored data, read reference/schema-changes.md and follow it: it finds every change to stored data and classifies it with § Breaking and additive changes. In short:
- Decide from evidence (the README, the user; not a directory name alone) whether the app is deployed, or unreleased or a sample or demo that shares its database with no released app; if unknown, assume deployed and say so. In a sample, a breaking change is not a defect: note that every peer, including a Ditto Server, needs an empty store.
- Classify the fixes too: a fix that, for example, turns an array into a map, a register into a counter,
statusinto a log, orDELETEinto soft delete changes stored data. In a deployed app, write it as a new field or collection next to the old one, marked breaking with the conditions in§ A field that replaces another(a collection:§ Rolling out a breaking change); never as a conversion in place.
Step 9: Report
Readers may not know Ditto. Start with a summary:
Verdict: <one sentence: for example, "two CRITICAL defects lose data when tills work offline; fix before release">
Findings: <n> CRITICAL, <n> HIGH, <n> MEDIUM (for a diff: <n> introduced by the change)
First actions: <up to three fixes, most important first>
Breaking changes to stored data: <each, or "none">
Then order findings by severity (CRITICAL: data loss, wrong results, crashes, security; HIGH: sync cost, memory, performance; MEDIUM: maintainability). For each finding:
[SEVERITY] file:line - <one-line problem>
Also: <other places of the same root cause, file:line each; omit if none>
Scenario: <for a finding that needs two devices or two app versions: the shortest sequence of events that produces it; omit otherwise>
Impact: <what goes wrong at runtime, and when>
Fix: <the concrete change, with a short code or DQL snippet if useful>
Schema: <additive or breaking, and why, when the problem or the fix changes stored data; omit otherwise>
Reference: <skill name> / § <guide heading> (<link>)
The link lets readers in the app's repository open the section: https://github.com/ditto-examples/ditto-cookbook/blob/main/<page>#<anchor>, where <page> is the page's path in the repository, such as best-practices/dql.md, and <anchor> is the heading in lowercase, with spaces turned into - and other punctuation except - removed. When the user asks you to post the review on a pull request, make each finding one review comment at its file:line, and the summary the review body.
End with: the guide version (the Version line of best-practices/README.md), the SDK version and platforms reviewed, whether the app was taken as deployed or a sample and why, the changes to stored data in the code under review (each additive or breaking), the inventory in compact form (per collection: subscriptions, reads, writes, removals), the areas checked with no findings, and anything not checked (for example code that was not available, which devices write a collection, how long devices stay offline, or behavior that needs a multi-device test). When a fact that the code cannot show, such as the platforms or the connection mode in step 2, is unknown, say so there instead of guessing. Mark findings that depend on a Note (SDK ...) behavior or on § Known Issues in SDK 5.1.0 as version-specific, and name the releases they apply to.
Scanner Limits
- Line-based: string literals joined across lines are read as one statement, but DQL built in another function can be missed.
- Not detectable: everything in steps 5, 6, and 8 (checks used as locks, values written back after a read in app code, results taken as complete, queries wider than their subscriptions), nested transactions through helper methods, observers or subscriptions registered in render code (except in a JavaScript component body:
register-in-render), subscription scope design, array-vs-map decisions, eviction that overlaps an active subscription, missing indexes. - Example and test code that demonstrates anti-patterns on purpose produces hits; treat them as such.
More
- The inventory, the eight questions with what to look for in code, when a question does not apply, and how to report: reference/cross-device-review.md
- Deployed or sample, finding and classifying changes to stored data, fixes, and the
Schemaline: reference/schema-changes.md - Scanner rules, patterns, and the guide section behind each: reference/scanner-rules.md
- Scanner source: scripts/scan.py
- Full guide search: the
guideskill
04 同仓库更多 Skills
Ditto 事务与附件处理
transactions-attachments
Ditto SDK 的事务与附件(Flutter、JavaScript、Kotlin、Swift):ditto.store.transaction 仅使用 tx.execute、不嵌套、作用域要短、回滚、close();newAttachment、ATTACHMENT 声明、带停顿超时(stall timeout)的惰性 fetchAttachment、不可变性、缩略图以及 blob 可用性。适用于编写或审查 ditto.store.transaction、newAttachment 或 fetchAttachment 代码,或展示存储在 Ditto 中的照片或文件。
Ditto SDK 测试策略与实现
testing
Flutter、JavaScript、Kotlin 或 Swift 中的 Ditto SDK 测试策略:本地存储测试辅助工具、DQL 语句测试、MISSING/NULL 过滤、合并敏感写入、软删除、观察者(observer)生命周期、订阅规则,以及在单进程中运行的多节点同步测试。适用于为使用 Ditto 的代码编写或审查测试、搭建 Ditto 测试框架(test harness),或复现 Ditto 同步或合并缺陷。
Ditto 数据删除与存储管理
storage-lifecycle
Ditto SDK 的数据删除与本地存储管理,涵盖 DELETE、软删除与 EVICT 之间的区别、墓碑(tombstone)及其 TTL、空壳文档(husk document)、配合补充订阅的驱逐(eviction)、保留期清理以及存储监控。适用于编写 Ditto 的 DELETE 或 EVICT 语句、为 Ditto 文档设置软删除标记或保留清理、处理 TOMBSTONE_TTL_HOURS,或处理已删除的 Ditto 数据重新出现、被驱逐的文档又同步回来的情况。
Ditto SDK 初始化配置与安全
sdk-setup
Ditto SDK 的设置、生命周期与生产环境安全(Flutter、JavaScript、Kotlin、Swift):DittoConfig、认证过期处理器、系统参数、同步启动与停止、关闭、传输(transports)、在线状态(presence)、密钥、权限、撤销。适用于初始化 Ditto、编写 Ditto 登录、启动、关闭或后台代码、配置 Ditto 传输、审查 Ditto 安全,或当 Ditto 同步始终无法启动、设备无法连接时。
Ditto DQL 查询与数据同步
query-sync
Ditto SDK 的 DQL 读写、订阅和存储观察器(Flutter、JavaScript、Kotlin、Swift):查询参数、MISSING 与 NULL 的区别、成员资格过滤器、订阅与观察器的生命周期、ON ID CONFLICT 更新插入(upsert)、JOIN、RETURNING。适用于在使用 Ditto 的应用中编写或审查 ditto.store.execute、ditto.sync.registerSubscription、registerObserver 或 DQL,或当 Ditto 数据无法同步、Ditto 查询返回空结果时。
Ditto 观察器性能诊断
performance-observability
Ditto SDK 存储观察器的性能与诊断(Flutter、JavaScript、Kotlin、Swift):观察器生命周期、背压(registerObserverV2、signalNext、挂起处理器)、精细 UI 更新、差异比较(differs)、冗余写入、索引、ADVISE、EXPLAIN、PROFILE、日志记录,以及 system: 集合。当 Ditto 查询缓慢、显示 Ditto 数据的界面卡顿、Ditto 观察器内存增长、Ditto upsert 重复执行,或需要设置 Ditto 日志记录时使用。