Skip to content

Merkle Trees, Read Repair, Anti-Entropy & Tombstones ​

"To detect the inconsistencies between replicas faster and to minimize the amount of transferred data, Dynamo uses Merkle trees." — DeCandia و همکاران، Dynamo: Amazon's Highly Available Key-value Store، SOSP 2007، بخش 4.7

خلاصه (Summary): replicaهایی که مستقل از هم نوشتن را می‌پذیرند به‌تدریج از هم فاصله می‌گیرند. یک store آن‌ها را از سه مسیر به هم نزدیک می‌کند: hint در مسیر نوشتن، read repair در مسیر خواندن، و ترمیم ضدآنتروپی (Anti-Entropy Repair) با درخت مرکل در پس‌زمینه. این کار برای حذف فقط وقتی امن است که خودِ حذف هم داده باشد، یعنی یک سنگ‌قبر (Tombstone)، و آن‌قدر بماند که به همهٔ replicaها برسد. تمرکز (Focus): درخت مرکل یا درخت هش (Merkle Tree / Hash Tree) از مقالهٔ مرکل در ۱۹۷۹ (برگ، گره‌های داخلی، root hash، branching factor، عمق، مسیر احراز)؛ inclusion proof و consistency proof در RFC 6962 و RFC 9162 (Certificate Transparency)؛ content addressing در Git؛ anti-entropy از Demers و همکاران (۱۹۸۷) و بخش 4.7 مقالهٔ Dynamo؛ full repair و incremental repair در Cassandra، SSTableهای repaired و unrepaired، anticompaction، گزینه‌های nodetool repair، subrange repair، Reaper و Auto Repair؛ active anti-entropy در Riak و row-level repair در ScyllaDB؛ read repair با digest request، digest mismatch، حالت BLOCKING در برابر NONE و حذف read_repair_chance در Cassandra 4.0؛ hinted handoff و max_hint_window؛ tombstone (delete marker، death certificate)، resurrection و zombie data، gc_grace_seconds، آستانه‌های tombstone و TombstoneOverwhelmingException، range tombstone و TTL tombstone، compaction که آن‌ها را پاک می‌کند؛ Kafka tombstone و delete.retention.ms؛ XDEL در Redis Streams؛ soft delete در برابر tombstone در SQL و Laravel (SoftDeletes، Prunable، model:prune)؛ همگام‌سازی کلاینت (CouchDB replication، endpoint مرکلی، rolling checksum در rsync)؛ observability ترمیم و tombstone؛ همراه با کتابخانهٔ مرکل و شبیه‌ساز replica در Go، کد SQL و Laravel 13، و آزمایشگاه. هدف یادگیری (Learning goal): توضیح دهید چرا درخت مرکل هزینهٔ مقایسهٔ دو replica را متناسب با تفاوت‌ها می‌کند نه با حجم داده، یک inclusion proof را با دست وارسی کنید، برای هر نوع واگرایی سازوکار درست همگرایی را انتخاب کنید، و حذف را (tombstone، دورهٔ مهلت، آهنگ repair، pruning) طوری طراحی کنید که دادهٔ حذف‌شده هرگز برنگردد؛ در Cassandra، Kafka، PostgreSQL و یک API آفلاین‌محور در Laravel.

این فصل در گروه Distributed Systems Primitives است و صاحب سازوکار ترمیم و حذفی است که سیستم‌های leaderless و eventually consistent زیر وعدهٔ سازگاری خود اجرا می‌کنند. خود توابع هش (SHA-2، BLAKE3، CRC) در Checksums & Hashing آمده‌اند؛ انتخاب CAP که واگرایی را ممکن می‌کند در CAP & PACELC؛ توپولوژی‌های quorum و حل تعارض در Replication Topologies؛ مدل‌های رسمی در Consistency Models؛ پخش عضویت و تشخیص خرابی در Gossip Protocols؛ نسخه‌های هم‌زمان در Vector Clocks؛ مقدارهای ادغام‌پذیر در CRDTs؛ ذخیره‌سازی LSM و درونیات compaction در Storage Engines؛ عملیات Cassandra به‌تفصیل در Cassandra & ScyllaDB in Depth و Wide-Column & Key-Value at Scale؛ eventual consistency در سطح موتور در Eventual Consistency in Database Systems؛ ذخیره‌سازی blob با آدرس‌دهی محتوایی در Object Storage؛ log compaction به‌عنوان قابلیت broker در Kafka in Depth؛ پاک‌کردن داده در logهای تغییرناپذیر در Messaging Security. نسخهٔ انگلیسی: /system-design/merkle-trees-anti-entropy.

نقشهٔ صفحه ​

دنبال چه هستیدبروید به
کل صفحه در سه جدولهمه‌چیز در یک دقیقه
چرا replicaها واگرا می‌شوند و چرا حذف بخش سخت استچرا وجود دارد
مرکل ۱۹۷۹، Demers ۱۹۸۷، rsync، Dynamo ۲۰۰۷، RFC 6962از کجا آمده
درخت هش چیست و دو درخت چطور مقایسه می‌شونددرخت مرکل، شکل درخت: branching factor و عمق
اثبات بودن یک رکورد در log، اثبات این‌که log فقط بزرگ شدهInclusion proof، Consistency proof
شیءهای Git، Certificate Transparency، بلاک‌چینContent addressing، Certificate Transparency
ترمیم پس‌زمینه بین replicaهاAnti-entropy، ترمیم در محصولات
Full در برابر incremental، SSTableهای repaired، anticompactionFull repair و incremental repair
nodetool repair، -pr، subrange، Reaper، Auto Repairاجرای repair
Digest request، digest mismatch، blocking read repairRead repair، read_repair_chance
Hint و hint windowHinted handoff
Delete marker، zombie، gc_grace_secondsTombstone، Resurrection
هشدار و شکست tombstone، range و TTL tombstoneسربار tombstone، انواع tombstone
مقدار null در Kafka، delete.retention.ms، XDEL در RedisTombstone در logها
deleted_at، SoftDeletes، PrunableSoft delete در برابر tombstone
کلاینت‌های آفلاین، CouchDB، rsyncپروتکل‌های همگام‌سازی کلاینت
چه چیزی را نمودار و هشدار کنیمObservability
فرمول‌ها، تنظیم‌ها، پیام‌های خطاسازوکار
کدGo، Laravel
حادثه‌ها و راه‌حل‌شانحل مسئله‌های کلاسیک
کدام سازوکار و کدام راهبرد حذف، کجاانتخاب
از یک پردازه تا چند regionدر معماری
خودتان اجرا کنیدآزمایشگاه
باورهای غلط، چکیده، آزمون، واژه‌هابدفهمی‌ها، چکیده، خودآزمایی، واژه‌نامه

همه‌چیز در یک دقیقه ​

سه مسیر همگرایی (نام‌ها از Cassandra، ریشه در Dynamo).

سازوکارکجا اجرا می‌شودچه را درست می‌کندچه را درست نمی‌کندتنظیم اصلی
Hinted handoffمسیر نوشتن: coordinator نوشتن را برای replica خاموش نگه می‌دارد و بعداً بازپخش می‌کندقطعی‌های کوتاه (restart، نگهداری)قطعی طولانی‌تر از hint window؛ فایل hint ازدست‌رفته؛ داده‌ای که هرگز به coordinator نرسیدmax_hint_window (پیش‌فرض 3h)، hinted_handoff_enabled
Read repairمسیر خواندن: digest mismatch بین replicaهایی که یک خواندن سراغشان رفتکلیدهای داغی که با سطح سازگاری بالاتر از ONE خوانده می‌شوندکلیدهایی که کسی نمی‌خواند؛ replicaهایی که خواندن سراغشان نرفتگزینهٔ جدول read_repair = BLOCKING (پیش‌فرض) یا NONE
ترمیم anti-entropyپس‌زمینه: درخت مرکل برای هر token range، فقط تفاوت‌ها stream می‌شوندهمه‌چیز، از جمله دادهٔ سرد و قطعی طولانیهیچ، اگر به‌اندازهٔ کافی اجرا شود؛ تنها تضمین همین استnodetool repair (پیش‌فرض incremental، --full)، Reaper، Auto Repair

حذف در سیستم‌های تکثیرشده و log-structured.

محصولحذف چه می‌نویسدنشانگر چقدر می‌ماندچه چیزی پاکش می‌کندچه چیزی خراب می‌شود
Cassandra، ScyllaDBیک tombstone با timestamp (cell، row، range یا partition)gc_grace_seconds برای هر جدول، پیش‌فرض 864000 (۱۰ روز)Compaction، وقتی دورهٔ مهلت گذشته و همهٔ دادهٔ قدیمی‌تر در همان compaction استreplicaای که در دورهٔ مهلت repair نشود: ردیف زنده می‌شود (zombie)
Kafka (topic فشرده‌شده)رکوردی با key و مقدار nulldelete.retention.ms، پیش‌فرض 86400000 (۱ روز)Log cleanerمصرف‌کننده‌ای که بیش از delete.retention.ms عقب باشد، حذف را نمی‌بیند
CouchDBیک revision تازه با _deleted: trueتا purgePOST /{db}/_purgeشناسهٔ purgeشده دیگر به‌عنوان حذف‌شده replicate نمی‌شود
Redis StreamsXDEL ورودی را درون macro node خود حذف‌شده علامت می‌زندتا وقتی همهٔ ورودی‌های node حذف شوندحافظه وقتی کل node خالی شد آزاد می‌شودهیچ delete marker تکثیرشده‌ای برای مصرف‌کننده‌ها نیست؛ consumer group فقط ورودی را نمی‌بیند
PostgreSQL / MySQL با soft deleteUPDATE ... SET deleted_at = now()سیاست نگهداری شمایک DELETE زمان‌بندی‌شده در دسته‌هافراموش‌کردن WHERE deleted_at IS NULL؛ prune پیش از همگام‌شدن همهٔ مصرف‌کننده‌ها
Laravel EloquentSoftDeletes: delete() مقدار deleted_at را می‌گذاردکوئری prunable() شماphp artisan model:prune (مدل‌های soft-deleted منطبق را forceDelete می‌کند)مهلت prune کوتاه‌تر از طولانی‌ترین کلاینت آفلاین

درخت مرکل بیرون از دیتابیس‌ها.

کجابرگ‌هاroot (یا یک hash) چه می‌خرداثبات مورداستفاده
ترمیم در Dynamo، Cassandra، Riakهش دادهٔ یک کلید یا token rangeدو replica یک hash را مقایسه می‌کنند و فقط به بازه‌های متفاوت پایین می‌روندTree diff
Certificate Transparency (RFC 6962)`SHA-256(0x00entry)` برای هر گواهی ثبت‌شده
Gitشیءهای blob (محتوای فایل)، tree (پوشه)، commitشناسهٔ commit کل snapshot را نام می‌بردContent address: محتوای یکسان، شناسهٔ یکسان
بلاک‌چین‌های شبیه Bitcoinهش تراکنش‌هاheader بلاک به همهٔ تراکنش‌ها متعهد استمسیر inclusion (simplified payment verification)
rsyncchecksum غلتان ضعیف + checksum قوی برای هر بلاکفقط بلاک‌های جورنشده فرستاده می‌شونددرخت نیست: فهرستی تخت از checksum بلاک‌ها
CouchDB replicationهیچ: changes feed و checkpoint_revs_diff می‌پرسد مقصد کدام revisionها را ندارددرخت نیست: checkpoint روی sequence
Three ways replicas converge: write path, read path, backgroundcoordinatorwrite x, RF=3replica n3 downstore hint locallyn3 returnsreplay hintdown past hint windowno hint: needs repairfull read + digestsCL replicasdigest mismatchfetch full datanewest timestamp winsmerge cellsblocking writeto stale, then replybuild Merkle treesone per token rangecompare treeswith each replicastream rangesthat differanticompactionrepaired / unrepairedWrite pathhinted handoffreach: best effort, hoursRead pathread repairreach: only keys that are readBackgroundanti-entropy repairreach: everything, incl. cold dataCassandra: hints and read repair are best effort; only full or incremental repair guarantees convergence.

این تصویر کل صفحه در سه خط است. hint ارزان و سریع است اما hint window محدودش می‌کند؛ read repair مجانی است اما فقط به چیزی که خوانده می‌شود می‌رسد؛ ترمیم با درخت مرکل گران است اما تنها مسیری است که تضمین می‌کند هر replica بالاخره هر نوشتن و هر حذف را داشته باشد. tombstoneها همان چیزی هستند که حالت حذف را در هر سه مسیر کارا می‌کنند.

چرا وجود دارد ​

یک store بی‌رهبر (Leaderless) نوشتن را وقتی می‌پذیرد که W از N replica تأیید کنند. بقیه ممکن است در حال restart، زیر بار یا جدا افتاده باشند؛ پس بعضی replicaها بعضی نوشتن‌ها را از دست می‌دهند. مستندات Cassandra صریح می‌گوید: "Hints attempt to inform a node of missed writes, but are a best effort, and aren't guaranteed to inform a node of 100% of the writes it missed. These inconsistencies can eventually result in data loss as nodes are replaced or tombstones expire." چیزی باید این تفاوت‌ها را پیدا و درست کند، بی‌آن‌که هر شب کل داده بین هر جفت replica کپی شود.

حذف بخش سخت ماجراست. replicaای که یک update را از دست داده مقدار قدیمی‌تری دارد و timestamp می‌گوید کدام تازه‌تر است. اما replicaای که یک حذف را از دست داده مقدار دارد و بقیه هیچ ندارند. «هیچ» timestamp ندارد؛ پس فرایند ترمیم یک replica با داده و دو replica بی‌داده می‌بیند و داده را برمی‌گرداند. Demers و همکاران این را در ۱۹۸۷ توصیف کردند: "the propagation mechanism will spread old copies of the item from elsewhere in the database back to the site where we have deleted it." راه‌حل این است که حذف را داده کنیم (death certificate، tombstone) و آن‌قدر نگهش داریم که همهٔ replicaها دیده باشندش.

همگرایی ارزانهمگرایی تضمین‌شده
فقط hint و read repairترمیم anti-entropy زمان‌بندی‌شده
بی I/O پس‌زمینهداده را روی همهٔ replicaها می‌خواند تا درخت بسازد و تفاوت‌ها را stream می‌کند
چیزی را درست می‌کند که اخیراً نوشته یا خوانده شدههمه‌چیز را درست می‌کند، از جمله دادهٔ سرد
دادهٔ حذف‌شده پس از قطعی طولانی می‌تواند برگردداگر ترمیم در دورهٔ مهلت اجرا شود، حذف‌ها حذف می‌مانند
مناسب کش و داده‌ای که می‌توان دوباره ساختلازم برای هر چیزی که حذفش می‌کنید و نباید دوباره ببینید

تصویر روزمره‌ای که در کل صفحه به کار می‌رود: سه شعبهٔ یک باشگاه هرکدام نسخه‌ای از دفتر اعضا دارند. هر شب هر شعبه جمع هر صفحه را روی یک کارت می‌نویسد و جمع همهٔ صفحه‌ها را هم در یک عدد برای کل دفتر. مقایسهٔ دو دفتر با همان یک عدد شروع می‌شود؛ اگر برابر بود، کسی دفتر را باز نمی‌کند. اگر نبود، جمع بخش‌ها را مقایسه می‌کنند، بعد جمع صفحه‌ها را، و فقط آخر کار سطرهای همان یک صفحهٔ متفاوت را. وقتی عضوی می‌رود، شعبه آن سطر را پاره نمی‌کند؛ با قرمز می‌نویسد «انصراف در ۳ اردیبهشت»، چون سطر پاره‌شده درست شبیه سطری است که شعبه‌های دیگر هرگز نداشته‌اند و آن‌ها با حسن نیت دوباره کپی‌اش می‌کنند. بعد از یک ماه، وقتی مطمئنیم همهٔ شعبه‌ها سطر قرمز را دیده‌اند، هم سطر و هم یادداشت را می‌شود برداشت.

سه بدفهمی رایج، از همان ابتدا ​

  1. «خواندن و نوشتن quorum ترمیم را غیرلازم می‌کند.» quorum فقط احتمال این را بالا می‌برد که یک خواندن آخرین نوشتن تأییدشده را ببیند. آن نوشتن را به replicaهایی که جا انداخته‌اند کپی نمی‌کند؛ خرابی بعدی replicaهایی که داده را دارند، یا حذفی که یک replica ندیده، هنوز داده را گم یا زنده می‌کند. Cassandra دربارهٔ hint و read repair می‌گوید: "are best effort and not an alternative to performing full repair."
  2. «درخت مرکل یک قابلیت امنیتی است.» در ترمیم، یک بهینه‌سازی پهنای باند و خواندن دیسک است. Dynamo می‌گوید درخت مرکل "minimize the amount of data that needs to be transferred for synchronization and reduce the number of disk reads performed during the anti-entropy process." کاربرد امنیتی (log ضددستکاری، inclusion proof) کاربرد دیگری از همان ساختار است.
  3. «حذف یک ردیف آن را حذف می‌کند.» در Cassandra، ScyllaDB، compaction در Kafka، CouchDB و هر موتور LSM، حذف یک نوشتن است: فضا می‌گیرد، خواندن‌هایی را که از رویش رد می‌شوند کند می‌کند، باید به‌اندازهٔ کافی بماند و بعد compaction پاکش کند. "Cassandra treats a deletion as an insertion, and inserts a time-stamped deletion marker called a tombstone."

از کجا آمده ​

text
     Year   Who / what                                   What it added
1    1979   Ralph Merkle, "A Certified Digital           "Tree authentication": H(i,j,Y) built by divide and conquer;
            Signature" (published Crypto '89)            root R; authentication path of log2 n hashes
2    1987   Demers et al., "Epidemic Algorithms for      Anti-entropy and rumor mongering for the Xerox Clearinghouse;
            Replicated Database Maintenance" (PODC)      "death certificates" so deletes are not resurrected
3    1990s  Tridgell & Mackerras, "The rsync             Weak rolling checksum + strong checksum per block;
            algorithm" (tech report)                     send only the blocks the other side lacks
4    2007   DeCandia et al., Dynamo (SOSP)               Sloppy quorum, hinted handoff (4.6), Merkle-tree anti-entropy
                                                         per key range (4.7), read repair
5    1.3    Riak KV 1.3                                  Active anti-entropy: persistent on-disk hash trees, updated
                                                         on every write, rebuilt weekly
6    2013   RFC 6962, Certificate Transparency           MTH with 0x00/0x01 domain separation, audit paths,
            (Experimental, June)                         consistency proofs
7    4.0    Apache Cassandra 4.0                         read_repair_chance removed; table option read_repair
                                                         (BLOCKING / NONE); incremental repair reworked
8    2021   RFC 9162, CT 2.0 (December)                  Obsoletes RFC 6962; exact verification algorithms
9    5.0.8  Cassandra Auto Repair (CEP-37, in 6.0,       Repair scheduler inside Cassandra itself
            backported to 5.0.8)

مرکل (۱۹۷۹). مسئله امضای پیام‌های زیاد با امضاهای یک‌بارمصرف بود، بی‌آن‌که همهٔ مقدارهای عمومی ذخیره شوند. پاسخ او: مقدارها را دوبه‌دو تا یک ریشه هش کن، ریشه را منتشر کن، و هر مقدار را همراه هش‌هایی بفرست که برای بازسازی ریشه لازم است. "The method is called tree authentication because the computation of H(1,n,Y) forms a binary tree of recursive calls." او متوجه نیمی از هش‌ها هم شد که لازم نیست فرستاده شوند: "to authenticate Y5 only required that we have previously authenticated H(1,8,Y), and that we transmit Y5, H(6,6,Y), H(7,8,Y), and H(1,4,Y)". این فهرست همان چیزی است که RFC 6962 بعدها مسیر حسابرسی (Audit Path) نامید.

Demers و همکاران (۱۹۸۷). آن‌ها روی سرویس نام Clearinghouse در Xerox کار می‌کردند و ارسال مستقیم، ضدآنتروپی (Anti-Entropy) و rumor mongering را مقایسه کردند. anti-entropy ساده‌ترین است: "every site regularly chooses another site at random and by exchanging database contents with it resolves any differences between the two." همان مقاله مسئلهٔ حذف و سنگ‌قبر را هم نام می‌برد: "we replace deleted items with death certificates, which carry timestamps and spread like ordinary data,"، و همان بده‌بستانی را می‌گوید که gc_grace_seconds هنوز در خود دارد: "increasing the time threshold reduces the risk but increases the amount of space consumed by death certificates." خود پخش gossip در Gossip Protocols آموزش داده شده است.

rsync. یک نقطهٔ مقابل، نه درخت: گیرنده checksumهای ضعیف و قوی بلاک‌های هم‌اندازهٔ فایلش را می‌فرستد و فرستنده یک checksum غلتان (Rolling Checksum) را روی فایل خودش می‌لغزاند تا تطابق را در هر offset پیدا کند. "The algorithm identifies parts of the source file which are identical to some part of the destination file, and only sends those parts which cannot be matched in this way."

Dynamo (۲۰۰۷). قطعه‌ها را برای یک store تولیدی کنار هم گذاشت: sloppy quorum با hinted handoff برای خرابی‌های گذرا، درخت مرکل برای هر بازهٔ کلید برای «خرابی دائمی»، و read repair. هزینهٔ عملیاتی را هم ثبت کرد: "when a node joins/leaves the system, the key ranges handled by many nodes change and the Merkle trees for the new ranges need to be recalculated, which is a non-trivial operation to perform on a production system."

Cassandra، Riak، ScyllaDB. Cassandra ترمیم Dynamo را به ارث برد و sub-range repair و incremental repair را افزود؛ Riak 1.3 آن را با درخت‌های ماندگار پیوسته کرد؛ ScyllaDB تبادل درخت را با checksum سطح ردیف و set reconciliation جایگزین کرد. Cassandra 4.0 read repair احتمالیِ پس‌زمینه را حذف کرد و Cassandra 6.0 (backport شده به 5.0.8) یک زمان‌بند repair درون‌پردازه‌ای دارد.

Certificate Transparency (۲۰۱۳، ۲۰۲۱). درخت مرکل را روی logهای عمومی و فقط‌افزودنی گواهی‌های TLS به کار برد، جایی که ریشه امضا می‌شود و هر کسی می‌تواند اثبات بخواهد. RFC 9162 جای RFC 6962 را گرفت و الگوریتم‌های وارسی را دقیق نوشت؛ کد Go همین صفحه همان‌ها را پیاده می‌کند.

فهرست مفاهیم ​

هر بلوک یک ترتیب دارد: به زبان ساده، باور غلط رایج، تعریف، timeline یا جریان درخواست، سناریوهای واقعی، رفتار محصولات، و راه‌حل.

درخت مرکل (Merkle Tree / Hash Tree) حیاتی ​

به زبان ساده: هر تکه داده را هش کنید؛ بعد هش‌ها را دوتادوتا (یا گروه‌گروه) هش کنید؛ تا وقتی یک هش بماند ادامه دهید. آن هش بالایی، یعنی root hash، با تغییر هر تکه عوض می‌شود. پس دو ماشین با مقایسهٔ ۳۲ بایت می‌فهمند «یکسانیم» یا نه، و اگر نه، با مقایسهٔ چند هش دیگر در مسیر پایین تکهٔ متفاوت را پیدا می‌کنند.

بدفهمی رایج: «برای مقایسهٔ دو replica با درخت مرکل باید کل درخت را فرستاد.» هر بار یک سطح فرستاده می‌شود و فقط زیر گره‌هایی که فرق دارند. Dynamo: "each branch of the tree can be checked independently without requiring nodes to download the entire tree or the entire data set."

تعریف: درختی که هر برگ (Leaf) آن هش یک بلوک داده و هر گرهٔ داخلی آن هش فرزندانش را نگه می‌دارد. Dynamo: "A Merkle tree is a hash tree where leaves are hashes of the values of individual keys. Parent nodes higher in the tree are hashes of their respective children." RFC 6962 یک شکل مشخص را تثبیت می‌کند: MTH({d(0)}) = SHA-256(0x00 || d(0)) برای برگ و MTH(D[n]) = SHA-256(0x01 || MTH(D[0:k]) || MTH(D[k:n])) برای n > 1، که k بزرگ‌ترین توان دو کوچک‌تر از n است. این دو پیشوند جداسازی دامنه‌اند: "This domain separation is required to give second preimage resistance."

Anti-entropy: compare roots, descend only where hashes differReplica ArootH(0-3)H(4-7)0-12-34-56-7R0R1R2R3R4R5R6R7Replica B (with R5 inclusion proof)rootH(0-3)H(4-7)0-12-34-56-7R0R1R2R3R4R5R6R7hash differs: ask for childrenhash equal: skip subtreeaudit path for R5: R4, H(6-7), H(0-3)Cost: 1 root + 2 + 2 + 2 = 7 hash comparisons for 8 ranges; with 2^20 ranges and one difference: 1 + 2 x 20 = 41.Only range R5 is streamed. Identical replicas exchange one root hash and stop.
text
     Replica A                               Replica B                       (8 token ranges)
1    send root(A)                    ->      compare with root(B): differ
2    send H(0-3), H(4-7)             ->      H(0-3) equal: skip 4 ranges; H(4-7) differs
3    send H(4-5), H(6-7)             ->      H(6-7) equal; H(4-5) differs
4    send H(R4), H(R5)               ->      R5 differs
5    stream the rows of range R5     <->     both sides merge by timestamp; 7 ranges untouched

تصویر بالا همین را نشان می‌دهد: ریشه‌ها فرق دارند، نیمهٔ چپ برابر است و رها می‌شود، و پایین‌رفتن فقط در شاخهٔ قرمز ادامه پیدا می‌کند تا بازهٔ R5. در درخت سمت راست، گره‌های زرد مسیر حسابرسی R5 هستند.

سناریوی واقعی: یک node در Cassandra که شش ساعت خاموش بوده برمی‌گردد و anti-entropy بین replicaهای یک جدول ۲۰۰ گیگابایتی چند بازهٔ تغییرکرده را پیدا و stream می‌کند؛ یک وارسی‌کنندهٔ backup ریشهٔ snapshot امروز را با دیروز مقایسه می‌کند تا ثابت کند در partitionهای سرد چیزی عوض نشده؛ یک اپ موبایل پیش از دانلود هر چیز یک ریشه را با سرور مقایسه می‌کند؛ یک monitor در Certificate Transparency وارسی می‌کند که گواهی موردنظرش در log هست، بی‌آن‌که log را دانلود کند.

محصولشکل درختبرگ‌هاچه زمانی ساخته می‌شود
Dynamo (مقاله)یک درخت برای هر بازهٔ کلید (virtual node)هش مقدار کلیدهادر هر node نگهداری می‌شود؛ با جابه‌جایی بازه‌ها از نو حساب می‌شود
Apache Cassandraیک درخت برای هر token range در هر جلسهٔ repair؛ وضوح محدود به repair_session_spaceهش partitionها در یک زیربازههنگام repair (validation compaction)، بعد دور ریخته می‌شود
Riak KV (AAE)درخت‌های هش ماندگار روی دیسکهش شیءهابا هر نوشتن به‌روز می‌شود؛ پیش‌فرض هفته‌ای یک بار از نو ساخته می‌شود
ScyllaDBبدون تبادل درخت: checksum سطح ردیف با set reconciliationردیف‌هاهنگام repair
logهای RFC 6962 / RFC 9162درخت دودویی پرشده از چپ روی فهرست فقط‌افزودنی`SHA-256(0x00
Gitیک tree object برای هر پوشه (دودویی نیست)شناسهٔ blob (هش محتوا)هنگام commit

راه‌حل / نحوهٔ استفاده: برای مقایسهٔ replica، درخت را روی بازه‌های ثابت کلید یا token بسازید تا دو طرف شکل یکسان داشته باشند؛ برای اثبات، از چیدمان RFC 6962 با پیشوندهای 0x00/0x01 استفاده کنید. بسته‌های merkle و antientropy در Go هرکدام یکی را انجام می‌دهند.

شکل درخت: برگ، branching factor، عمق و وضوح مهم ​

به زبان ساده: معمولاً هر برگ یک بازه از کلیدها را پوشش می‌دهد، نه یک کلید را. برگ بیشتر یعنی می‌توان به بازهٔ کوچک‌تری اشاره کرد که فرق دارد (دادهٔ کمتری stream می‌شود)، اما درخت حافظهٔ بیشتر و هش‌های بیشتری برای تبادل می‌خواهد. درخت پهن‌تر (فرزندان بیشتر برای هر گره، یعنی ضریب انشعاب (Branching Factor) بزرگ‌تر) سطح‌های کمتری دارد، پس رفت‌وبرگشت کمتر، اما هر گام هش بیشتری می‌فرستد.

بدفهمی رایج: «یک برگ برای هر کلید دقیق‌ترین است، پس بهترین است.» با یک میلیارد کلید یعنی یک میلیارد هش در حافظه برای هر بازه در هر repair. Cassandra به‌جایش حافظه را محدود می‌کند: پیش‌فرض repair_session_space برابر "1/16th of the available heap" است و "smaller trees have less resolution, which can lead to over-streaming data."

تعریف: برای درخت کامل با branching factor برابر b و عمق d تعداد b^d برگ داریم. مقایسهٔ دو درخت که در k برگ فرق دارند حداکثر d رفت‌وبرگشت و حدود 1 + k * b * d مقایسهٔ هش می‌خواهد؛ درخت‌های یکسان یک مقایسه. هزینهٔ stream دادهٔ همان k برگ واگراست، پس به تعداد کلید در هر برگ بستگی دارد: با n کلید و L برگ، یک کلید تغییرکرده حدود n / L کلید را stream می‌کند (over-streaming).

text
     One divergent key among 100000 (measured by the Go lab, cmd/aesim)
1    fanout 2,     depth 4   ->     16 buckets:  5 rounds,     9 hashes, 6110 keys streamed
2    fanout 2,     depth 16  ->  65536 buckets: 17 rounds,    33 hashes,    2 keys streamed
3    fanout 16,    depth 4   ->  65536 buckets:  5 rounds,    65 hashes,    2 keys streamed
4    fanout 256,   depth 2   ->  65536 buckets:  3 rounds,   513 hashes,    2 keys streamed
5    fanout 65536, depth 1   ->  65536 buckets:  2 rounds, 65537 hashes,    2 keys streamed (a flat list)

سناریوی واقعی: خوشهٔ Cassandra با partitionهای بزرگ که repair آن برای چند ردیف تغییرکرده گیگابایت‌ها stream می‌کند (وضوح کم: repair_session_space را بالا ببرید یا زیربازه‌های کوچک‌تر را repair کنید)؛ endpoint همگام‌سازی موبایل که ۲۵۶ bucket انتخاب می‌کند تا یک رفت‌وبرگشت با ۸ کیلوبایت هش bucketهای تغییرکرده را پیدا کند؛ همگام‌سازی بین regionها روی لینک ۱۵۰ میلی‌ثانیه‌ای که درخت پهن را ترجیح می‌دهد تا تعداد رفت‌وبرگشت کم بماند.

تنظیممحصولاثر
repair_session_spacecassandra.yaml در Cassandraحافظهٔ درخت مرکل برای هر جدول و بازه؛ حافظهٔ بیشتر یعنی وضوح بیشتر و over-streaming کمتر
concurrent_merkle_tree_requestsCassandraساخت هم‌زمان درخت‌ها را محدود می‌کند؛ پیش‌فرض 0 (بی‌حد) "can produce OOM"
-st / -et (subrange repair)nodetool repairکلید کمتر در هر درخت، پس وضوح بیشتر با همان حافظه
تعداد bucketAPI همگام‌سازی شمایک سطح ۲۵۶تایی یعنی ۸ کیلوبایت هش SHA-256 در هر مقایسه

راه‌حل / نحوهٔ استفاده: برگ‌ها را بر اساس مقدار داده‌ای انتخاب کنید که حاضرید برای هر تفاوت stream کنید، بعد fan-out را بر اساس تأخیر رفت‌وبرگشت. برای همگام‌سازی سرور با گوشی، دو سطح ۲۵۶تایی معمولاً کافی است.

اثبات عضویت (Inclusion Proof، Audit Path، Audit Proof) مهم ​

به زبان ساده: برای قانع‌کردن کسی که به ریشه اعتماد دارد که یک قلم در درخت هست، خود قلم و هش هم‌سایهٔ آن را در هر سطح تا بالا بفرستید. او ریشه را دوباره حساب می‌کند؛ اگر یکی شد، قلم در درخت است. با یک میلیون قلم یعنی ۲۰ هش.

بدفهمی رایج: «اثبات باید قلم‌های دیگر را هم داشته باشد.» فقط ceil(log2 n) هش دارد و وارسی‌کننده هیچ‌وقت قلم‌های دیگر را نمی‌بیند. اشتباه دیگر اعتماد به اثبات بدون ریشهٔ مورداعتماد است: اثبات قلم را فقط به همان ریشه‌ای گره می‌زند که با آن مقایسه می‌کنید.

تعریف: RFC 6962: "A Merkle audit path for a leaf in a Merkle Hash Tree is the shortest list of additional nodes in the Merkle Tree required to compute the Merkle Tree Hash for that tree. ... If the root computed from the audit path matches the true root, then the audit path is proof that the leaf exists in the tree." بخش 2.1.3.2 در RFC 9162 حلقهٔ وارسی را روی leaf_index و tree_size می‌دهد؛ VerifyInclusion در بستهٔ merkle ترجمهٔ خط‌به‌خط آن است. مرکل در ۱۹۷۹ اسمش را «authentication path» گذاشته بود.

text
     Verify leaf 5 of 8 with audit path [h4, h(6-7), h(0-3)]
1    r = leaf hash of d5
2    5 is odd       -> r = H(0x01 || h4 || r)          = h(4-5)
3    2 is even      -> r = H(0x01 || r || h(6-7))      = h(4-7)
4    1 is odd       -> r = H(0x01 || h(0-3) || r)      = root
5    compare r with the signed root: equal -> leaf 5 is in the tree

سناریوی واقعی: یک CT log به مرورگر signed certificate timestamp و بعداً inclusion proof می‌دهد؛ یک سرویس دفتر کل به حسابرس اثبات می‌دهد که یک تراکنش در ریشهٔ منتشرشدهٔ آن روز هست؛ یک کلاینت سبک بلاک‌چین پرداخت را با header بلاک می‌سنجد؛ یک سرویس اسناد ثابت می‌کند نسخه‌ای از قرارداد در زمانی وجود داشته، بی‌آن‌که قراردادهای دیگر را فاش کند.

راه‌حل / نحوهٔ استفاده: tree.InclusionProof(i, size) و merkle.VerifyInclusion(merkle.LeafHash(data), i, size, proof, root). همیشه با پیشوند برگ هش کنید: وارسی‌کننده‌ای که گرهٔ داخلی را به‌جای برگ بپذیرد در برابر همان حملهٔ second preimage باز است که پیشوندها برای جلوگیری‌اش هستند.

اثبات سازگاری (Consistency Proof) تکمیلی ​

به زبان ساده: یک log وقتی m ورودی داشت ریشهٔ R1 را منتشر کرد و حالا با n ورودی ریشهٔ R2 را. consistency proof چند هش است که نشان می‌دهد m ورودی اول عوض نشده‌اند، پس log فقط افزوده است.

بدفهمی رایج: «اگر همهٔ inclusion proofها درست باشند، log صادق است.» یک log می‌تواند به آدم‌های مختلف تاریخچه‌های مختلف نشان دهد (split view). consistency proof بین هر جفت tree head که دیده‌اید، به‌اضافهٔ gossip کردن tree headها بین monitorها، این شکاف را می‌بندد.

تعریف: RFC 6962 بخش 2.1.2: "Merkle consistency proofs prove the append-only property of the tree." اثبات برابر SUBPROOF(m, D[n], true) است و "the number of nodes in the resulting proof is bounded above by ceil(log2(n)) + 1." بخش 2.1.4.2 در RFC 9162 حلقهٔ وارسی را می‌دهد.

text
     Monitor                                         Log
1    stored: (size 600000, root R1)
2    GET consistency proof 600000 -> 1000000   ->
3                                              <-    15 hashes
4    recompute R1 and R2 from the same hashes
5    both match -> the first 600000 entries were not rewritten

سناریوی واقعی: یک CT monitor هر چند دقیقه tree headها را می‌گیرد؛ یک audit log ضددستکاری برای کنسول مدیریت که هر روز ریشه منتشر می‌کند و باید به حسابرس نشان دهد ورودی‌های هفتهٔ پیش ویرایش نشده‌اند؛ یک transparency log برای انتشار نرم‌افزار (پایگاه checksum در Go از همین ساختار درخت استفاده می‌کند) که به کلاینت اجازه می‌دهد انتشار جابه‌جاشده را کشف کند.

راه‌حل / نحوهٔ استفاده: هر tree headی را که وارسی کرده‌اید نگه دارید و با هر tree head تازه VerifyConsistency(oldSize, newSize, oldRoot, newRoot, proof) را صدا بزنید. تست TestRewrittenHistoryFailsConsistency نشان می‌دهد logی که ورودی ۲ را ویرایش کرده در این وارسی رد می‌شود.

آدرس‌دهی محتوایی (Content Addressing) و شیءهای Git تکمیلی ​

به زبان ساده: هر تکه داده را با هش محتوایش نام‌گذاری کنید. محتوای یکسان همیشه نام یکسان دارد، نام متفاوت یعنی محتوای متفاوت، و پوشه‌ای که نام فرزندانش را فهرست می‌کند خودش با یک هش نام‌گذاری می‌شود: یک درخت مرکل.

بدفهمی رایج: «Git فقط diff ذخیره می‌کند.» مدل شیء محتوای کامل را با آدرس هش ذخیره می‌کند و packfileها بعداً فشرده‌سازی می‌کنند. "Git is a content-addressable filesystem. ... at the core of Git is a simple key-value data store."

تعریف: Git شیءهای blob (محتوای فایل) و tree object نگه می‌دارد؛ "A single tree object contains one or more entries, each of which is the SHA-1 hash of a blob or subtree with its associated mode, type, and filename." یک commit به یک tree ریشه اشاره می‌کند، پس شناسهٔ commit به همهٔ بایت‌های snapshot متعهد است. دو مخزن با یک commit id مشترک کل درخت زیر آن را مشترک دارند؛ برای همین fetch فقط شیءهایی را منتقل می‌کند که طرف مقابل ندارد. خود هش‌کردن در Checksums & Hashing و ذخیره‌سازی blob با آدرس محتوا در Object Storage آمده است.

text
     git commit
1    blob   ce0136...  <- "hello\n"                      (file contents; id = SHA-1 of header + content)
2    tree   T1         <- 100644 blob ce0136... README    (directory listing names children by hash)
3    commit C1         <- tree T1, parent C0, author ...
4    edit README -> new blob id -> new tree id -> new commit id; unchanged subtrees keep their ids

سناریوی واقعی: حذف آپلودهای تکراری در object storage با SHA-256؛ کش build با کلید هش ورودی‌ها؛ لایه‌های image کانتینر با آدرس digest؛ content id به سبک IPFS؛ مذاکرهٔ fetch در Git برای این‌که کدام شیءها فرستاده شوند.

راه‌حل / نحوهٔ استفاده: وقتی برای یک سلسله‌مراتب سؤال «آیا عوض شده؟» دارید، فرزندان را هش کنید و هش آن‌ها را در والد نگه دارید. وقتی سؤال «آیا دقیقاً همین محتواست؟» است، با هش رمزنگارانه (SHA-256) آدرس بدهید، نه با CRC.

Certificate Transparency (RFC 6962) و بلاک‌چین تکمیلی ​

به زبان ساده: CT logها فهرست‌های عمومی و فقط‌افزودنی گواهی‌های TLS هستند. log ریشهٔ فعلی‌اش را امضا می‌کند (Signed Tree Head) و هر کسی می‌تواند برای یک گواهی inclusion proof یا بین دو ریشهٔ امضاشده consistency proof بخواهد. بلاک‌چین‌ها هم به همین دلیل ریشهٔ مرکل تراکنش‌های بلاک را در header آن می‌گذارند.

بدفهمی رایج: «CT و Cassandra درخت مرکل را یک‌جور به کار می‌برند.» CT آن را برای اثبات به طرف سوم بی‌اعتماد روی فهرست فقط‌افزودنی به کار می‌برد. Cassandra آن را بین replicaهای مورداعتماد برای پیدا کردن تفاوت در داده‌ای تغییرپذیر به کار می‌برد؛ درخت‌ها بعد از هر repair دور ریخته می‌شوند و هرگز امضا نمی‌شوند.

تعریف: RFC 6962: "Logs use a binary Merkle Hash Tree for efficient auditing." نمای کلی certificate.transparency.dev: "When the log server signs the root Merkle tree it creates a Signed Tree Head (STH)." RFC 9162 (CT 2.0) جای RFC 6962 را گرفته است.

text
     CA                    CT log                     Browser                 Monitor
1    submit precert  ->    add leaf, return SCT
2                          later: new STH (size n, root R, signature)
3                                                     cert + SCT ->  check SCT signature
4                                                                            GET inclusion proof, GET consistency(R_old, R)
5                                                                            alarm if a certificate for its domain appears

سناریوی واقعی: کشف گواهی اشتباه صادرشده برای دامنهٔ شما؛ حسابرسی انتشارهای نرم‌افزاری یک فروشنده از طریق transparency log؛ لنگرانداختن یک audit trail داخلی با انتشار ریشه‌های روزانه.

کاربردبه‌روزشدن درختچه کسی به چه کسی اعتماد دارداثبات‌ها
ترمیم در Cassandra / Dynamoدر هر repair از نوreplicaها به هم اعتماد دارندهیچ، فقط diff
CT logفقط افزودنیهیچ‌کس به log اعتماد نداردInclusion + consistency، ریشهٔ امضاشده
بلاک در بلاک‌چینبرای هر بلاکاجماع روی headerهامسیر inclusion تا header
Gitبرای هر committag امضاشده یا اعتماد به remoteشناسهٔ محتوا

راه‌حل / نحوهٔ استفاده: اگر audit log می‌سازید، درخت RFC 6962 با ریشه‌های منتشر (یا امضا)شده ابزار بهتری از hash chain است: inclusion proof لگاریتمی است و consistency proof رشد فقط‌افزودنی را نشان می‌دهد.

ضدآنتروپی (Anti-Entropy) حیاتی ​

به زبان ساده: یک کار پس‌زمینه که دو replica را وادار می‌کند همهٔ آنچه دارند را مقایسه کنند و هر چیزی را که یکی دارد و دیگری ندارد کپی کنند، چه کسی اخیراً آن را خوانده یا نوشته باشد چه نه. درخت مرکل فقط مقایسه را ارزان می‌کند.

بدفهمی رایج: «anti-entropy در هر دیتابیس شبیه Dynamo خودکار اجرا می‌شود.» در Riak KV، AAE "is enabled by default"؛ اما در Apache Cassandra: "since repair can result in a lot of disk and network io, it's not run automatically by Cassandra. It is run by the operator via nodetool" (یا با Reaper، یا با زمان‌بند Auto Repair در 6.0 و 5.0.8 اگر فعالش کنید). خوشهٔ Cassandra که کسی در آن repair اجرا نمی‌کند اصلاً anti-entropy ندارد.

تعریف: Demers و همکاران: "every site regularly chooses another site at random and by exchanging database contents with it resolves any differences between the two. Anti-entropy is extremely reliable but requires examining the contents of the database and so cannot be used too frequently." بخش 4.7 در Dynamo آن را بازه‌محور می‌کند: "Each node maintains a separate Merkle tree for each key range ... two nodes exchange the root of the Merkle tree corresponding to the key ranges that they host in common." مقدارهای ترمیم‌شده با قاعدهٔ عادی تعارض store ادغام می‌شوند (Cassandra: last-write-wins برای هر cell بر اساس timestamp؛ Dynamo/Riak: vector clock و sibling؛ Vector Clocks را ببینید).

text
     n1 (owns range R)                      n2 (replica of R)                n3 (replica of R)
1    repair session starts for R
2    request tree for R          ->         read R, build tree T2            read R, build tree T3
3    build T1                    <-         send T2                    <-    send T3
4    compare T1/T2, T1/T3, T2/T3: ranges R.17 and R.230 differ between n1 and n3
5    stream R.17, R.230 between n1 and n3 (both directions); n2 untouched
6    session done; trees discarded (Cassandra) or kept and updated (Riak AAE)

سناریوی واقعی: یک node یک روز خاموش بوده، بیش از hint window؛ دیسکی تعویض شده و node از backup کهنه بازسازی شده؛ replication factor افزایش یافته (Cassandra هشدار می‌دهد "When increasing replication factor you need to run a full (-full) repair to distribute the data")؛ یک datacenter ساعت‌ها جدا بوده؛ دادهٔ سردی که کسی نمی‌خواند هم باید همهٔ حذف‌هایش را پیش از تمام‌شدن gc_grace_seconds منتشر کند.

راه‌حل / نحوهٔ استفاده: زمان‌بندی‌اش کنید. مستندات Cassandra نقطهٔ شروع را می‌دهد: "running an incremental repair every 1-3 days, and a full repair every 1-3 weeks is probably reasonable" و حد سخت را: "repair should be run often enough that the gc grace period never expires on unrepaired data."

ترمیم با درخت مرکل در Dynamo، Cassandra، Riak و ScyllaDB حیاتی ​

به زبان ساده: هر store بی‌رهبری نسخه‌ای از طرح Dynamo را دارد، اما در این فرق دارند که درخت ماندگار است یا نه، repair چند وقت یک بار اجرا می‌شود، و آیا شما باید شروعش کنید.

بدفهمی رایج: «Amazon DynamoDB هم مثل Cassandra فرمان repair دارد.» مقالهٔ Dynamo store داخلی Amazon را توصیف می‌کند؛ سرویس DynamoDB همگام‌سازی داخلی replicaهایش را مستند نکرده و فرمان repair به شما نمی‌دهد. آنچه دارید انتخاب سازگاری برای هر خواندن است (ConsistentRead) که در CAP & PACELC آمده. هر چیزی دربارهٔ درونیات DynamoDB را استنباط (inference) بدانید.

تعریف: محصولات زیر replicaها را با هش روی بازه‌ها مقایسه می‌کنند و فقط دادهٔ متفاوت را stream می‌کنند؛ جدول تفاوت عملیاتی است.

text
     Cassandra full repair on one node, keyspace shop, table carts
1    nodetool repair --full shop carts
2    [..] Starting repair command #1 ..., repairing keyspace shop with repair options (parallelism: parallel,
         primary range: false, incremental: false, ...)
3    for each token range of this node: replicas build Merkle trees, compare, stream mismatches
4    [..] Repair session ... for range [(-8792657144775336505,-8786320730900698730], ...] finished
5    [..] Repair completed successfully

سناریوی واقعی: تیم عملیات Reaper را روی چند خوشهٔ Cassandra با برنامهٔ full هفتگی و incremental روزانه اجرا می‌کند؛ خوشهٔ Riak به AAE و read repair تکیه دارد و هیچ‌چیز زمان‌بندی نمی‌کند؛ خوشهٔ ScyllaDB از ScyllaDB Manager یا repair خودکار روی tabletها استفاده می‌کند.

محصولدرخت‌هاچه کسی repair را شروع می‌کندIncremental؟نکته
Dynamo (مقاله)برای هر بازهٔ کلید، در هر node نگهداری می‌شودخود سیستمنداردبا تغییر عضویت، درخت بازه‌ها از نو حساب می‌شود
Apache Cassandraبرای هر جلسهٔ repair ساخته و دور ریخته می‌شوداپراتور: nodetool repair، Reaper، یا Auto Repair (6.0؛ در 5.0.8 پشت -Dcassandra.autorepair.enable=true)بله، نوع پیش‌فرضsub-range repair وضوح درخت را بالا می‌برد
Riak KVماندگار، روی دیسک، با هر نوشتن به‌روزخود سیستم (AAE به‌طور پیش‌فرض روشن)پیوستهدرخت‌ها به‌طور دوره‌ای (پیش‌فرض هفته‌ای یک بار) از نو ساخته می‌شوند تا خرابی خاموش کشف شود
ScyllaDBchecksum سطح ردیف و set reconciliation، نه تبادل درختnodetool repair، ScyllaDB Manager، یا repair خودکاربله، روی tabletهامستندات: اگر زیاد حذف می‌کنید، repair را زودتر از gc_grace_seconds اجرا کنید
Amazon DynamoDBمستند نشدهخود سرویسنداردفقط استنباط

راه‌حل / نحوهٔ استفاده: در Cassandra تصمیم بگیرید صاحب repair کیست (یک زمان‌بند برای هر خوشه، هرگز دو تا)، وقتی آخرین repair موفق هر جدول قدیمی‌تر از gc_grace_seconds منهای یک حاشیه شد هشدار دهید، و incremental و full را با آهنگ جدا نگه دارید.

Full repair و incremental repair، SSTableهای repaired و anticompaction حیاتی ​

به زبان ساده: full repair همهٔ دادهٔ یک بازه را مقایسه می‌کند. incremental repair فقط داده‌ای را که از آخرین incremental repair نوشته شده مقایسه می‌کند و بعد آن را «repaired» برچسب می‌زند تا اجرای بعدی از رویش رد شود. خیلی ارزان‌تر است، اما هر چیزی با برچسب repaired دیگر هرگز در اجراهای incremental بررسی نمی‌شود.

بدفهمی رایج: «incremental repair جای full repair را می‌گیرد.» Cassandra: "once an incremental repair marks data as repaired, it won't try to repair it again. This is fine for syncing up missed writes, but it doesn't protect against things like disk corruption, data loss by operator error, or bugs in Cassandra. For this reason, full repairs should still be run occasionally."

تعریف: Cassandra دادهٔ repaired و unrepaired را در SSTableهای جدا نگه می‌دارد: "With anticompaction repaired data is split out into repaired and unrepaired SSTables. To avoid mixing up the data again separate compaction strategy instances are run on the two sets of data." خود ضدفشرده‌سازی (Anticompaction): "After repair, the ranges that were actually repaired are split out of the SSTables that existed when repair started." پیش‌فرض incremental است: nodetool repair؛ full یعنی nodetool repair --full.

Incremental repair keeps two worlds apart; full repair re-checks bothUnrepaired SSTablesnew writes, flushess1s2s3r1r2r3own compaction instancetombstones kept here whenonly_purge_repaired_tombstonesRepaired SSTablesmarked as repairedown compaction instancenever re-checked byincremental repairincremental repairMerkle trees over unrepaired onlyanticompactionsplit repaired ranges outfull repair (nodetool repair --full): Merkle trees over repaired + unrepairedcatches disk corruption, operator error and bugs; --validate checks repaired data, --preview estimates streaming
text
     Day   Command                      Trees over                    Then
1    1     nodetool repair             unrepaired SSTables            anticompaction: repaired set grows
2    2     nodetool repair             new unrepaired data only       cheap: yesterday's data is skipped
3    7     nodetool repair --full      repaired + unrepaired          catches a bit flip in a repaired SSTable
4    8     (incremental stopped)       -                              old repaired data blocks tombstone purge
                                                                      in newer unrepaired SSTables

سناریوی واقعی: خوشهٔ بزرگ time-series با incremental repair زمان repair را یک مرتبهٔ بزرگی کم می‌کند؛ تیمی که یک بار در تست incremental repair اجرا کرد و دیگر هرگز، tombstoneهایی پیدا می‌کند که پاک نمی‌شوند، چون "if you only run incremental repair once and then never again, you might have very old data in the repaired SSTables that block compaction from dropping tombstones in the unrepaired (probably newer) SSTables"؛ اپراتوری که پس از یک رخداد مشکوک دیسک nodetool repair --validate اجرا می‌کند.

گزینهچه می‌کند
nodetool repairincremental repair همهٔ بازه‌هایی که این node تکثیر می‌کند
--full / -fullfull repair
-pr، --partitioner-rangeفقط بازه‌های اصلی node؛ روی همهٔ nodeها اجرا کنید تا حلقه یک بار پوشش داده شود
-st، -etsubrange repair بین دو token
-prv، --preview"builds the merkle trees, and prints the expected streaming activity, but does not actually do any streaming"
-vd، --validateوارسی می‌کند دادهٔ repaired هم‌گام است؛ ناهم‌گامی یعنی full repair اجرا کنید
-dc، -local، -dcparمحدود به datacenterها یا repair موازی آن‌ها
-seqrepair ترتیبی (هر بار یک replica)
-jتعداد job thread، "default: 1, max: 4"
--pullrepair یک‌طرفه: فقط از node دور به این node stream شود

راه‌حل / نحوهٔ استفاده: incremental هر یک تا سه روز، full هر یک تا سه هفته، و هر دو با فاصلهٔ خوب درون gc_grace_seconds تمام شوند. اگر incremental را متوقف می‌کنید، بعدش یک full repair اجرا کنید و nodetool repair --full را تنها حالت در نظر بگیرید.

اجرای repair: -pr، زیربازه‌ها، Reaper، Auto Repair مهم ​

به زبان ساده: nodetool repair بازه‌های همان nodeی را repair می‌کند که رویش اجرا می‌شود، نه کل خوشه را. اگر ساده‌لوحانه روی همهٔ nodeها اجرایش کنید، هر بازه به تعداد replicaها repair می‌شود. ابزارهایی هستند که حلقه را به تکه‌های کوچک می‌شکنند، چندتایی اجرا می‌کنند و یادشان می‌ماند چه چیزی تمام شده.

بدفهمی رایج: «یک nodetool repair کل خوشه را repair می‌کند.» Cassandra: "The repair command repairs token ranges only on the node being repaired; it does not repair the whole cluster." و "By default, repair operates on all token ranges replicated by the node on which repair is run, causing duplicate work when running it on every node. Avoid duplicate work by using the -pr flag".

تعریف: repair کامل خوشه یعنی nodetool repair -pr "on each node in each datacenter in the cluster." ابزار Reaper "is a centralized, stateful, and highly configurable tool for running Apache Cassandra repairs for multi-site clusters" که repair را "at keyspace, table, or even token range level" زمان‌بندی می‌کند و "prevents overlapping repairs". Auto Repair در Cassandra "is a fully automated scheduler that provides repair orchestration within Apache Cassandra"، تاریخچه را در system_distributed.auto_repair_history نگه می‌دارد و "splits token ranges into subranges, with necessary retries to handle transient failures."

text
     Reaper, weekly schedule for keyspace shop (expected behaviour)
1    split the ring into segments (subranges)
2    run segment 1 on its replicas; at most one segment per node at a time
3    segment fails -> retry later; progress kept in Reaper's backend
4    all segments done -> record completion; next run in 7 days
5    alert if the run does not finish inside gc_grace_seconds

سناریوی واقعی: خوشهٔ ۶۰ nodeی که یک full repair برای یک node یک روز طول می‌کشید؛ رفتن به subrange repair هر جلسه را آن‌قدر کوچک نگه می‌دارد که بشود دوباره امتحانش کرد؛ خوشه‌ای که به 5.0.8 ارتقا یافته Auto Repair را روشن و cron jobها را بازنشسته می‌کند؛ تیمی که هم Reaper و هم cron اجرا می‌کند repairهای هم‌پوشان می‌بیند که I/O دیسک را دو برابر کرده‌اند.

راه‌حل / نحوهٔ استفاده: یک زمان‌بند، تکه‌های subrange، -pr اگر خودتان اسکریپت می‌نویسید، و یک مهلت پایش‌شده برابر gc_grace_seconds منهای حاشیه (مثال خود Cassandra: "With a default gc grace period of 10 days, repairing every node in your cluster at least once every 7 days will prevent this").

ترمیم هنگام خواندن (Read Repair): digest request، digest mismatch، blocking حیاتی ​

به زبان ساده: وقتی یک خواندن از چند replica می‌پرسد، coordinator دادهٔ کامل را از یکی و فقط یک هش (digest) از بقیه می‌گیرد. اگر هش‌ها یکی بود، تمام. اگر نه، دادهٔ کامل را می‌گیرد، تازه‌ترین نسخه را انتخاب می‌کند، آن را روی replicaهای عقب‌مانده می‌نویسد و تازه بعد جواب می‌دهد.

بدفهمی رایج: «read repair همهٔ replicaهای یک کلید را درست می‌کند.» فقط replicaهایی را که در آن خواندن درگیر بودند: "If read repair is performed it is made only on the replicas that are not up-to-date and that are involved in the read request." در ONE و LOCAL_ONE اصلاً digest request و read repair وجود ندارد.

تعریف: Cassandra: "A digest read request is not a full read and only returns the hash value of the data." در صورت ناهمخوانی digest (Digest Mismatch)، coordinator خواندن کامل می‌فرستد، با timestamp آشتی می‌دهد و با read_repair = 'BLOCKING' (پیش‌فرض) "the read will block on writes sent to other replicas until the CL is reached by the writes." این «monotonic quorum reads» می‌دهد: "in 2 successive quorum reads, it's guaranteed the 2nd one won't get something older than the 1st one". حالت NONE برای پاسخ آشتی می‌دهد اما چیزی برنمی‌نویسد و در عوض اتمی‌بودن نوشتن در سطح partition را حفظ می‌کند. Riak read repair را "a passive anti-entropy mechanism" می‌نامد؛ Dynamo: "This process is called read repair because it repairs replicas that have missed a recent update at an opportunistic time and relieves the anti-entropy protocol from having to do it."

text
     Client       Coordinator                    R1 (fresh)           R2 (stale)       CL = QUORUM, RF = 3
1    SELECT ->    full read to R1          ->    data v2 (ts 20)
2                 digest read to R2        ->                         digest(v1)
3                 digest(v2) != digest(v1): digest mismatch
4                 full read to R2          ->                         data v1 (ts 10)
5                 newest = v2; write v2    ->                         applied, ack
6    <- v2        (BLOCKING: reply only after the repair write reached CL)

سناریوی واقعی: خواندن پروفایل کاربر با LOCAL_QUORUM بی‌صدا replicaای را که آخرین update را جا انداخته درست می‌کند؛ جدول پرخواندن کلیدهای داغ را چند دقیقه پس از قطعی هم‌گام می‌کند ولی کلیدهای سرد تا repair واگرا می‌مانند؛ جدولی که در batchهای چندردیفی نوشته ولی تک‌ردیفی خوانده می‌شود read_repair = 'NONE' می‌گذارد چون "read repair can break write atomicity when data is read at a more granular level than it is written."

سطح سازگاری (Cassandra)Digest requestRead repair
ONE، LOCAL_ONEنداردانجام نمی‌شود
TWO، THREEدارددر صورت ناهمخوانی انجام می‌شود
QUORUM، LOCAL_QUORUMدارددر صورت ناهمخوانی انجام می‌شود
ALLدارددر صورت ناهمخوانی انجام می‌شود

راه‌حل / نحوهٔ استفاده: BLOCKING را نگه دارید مگر حالت اتمی‌بودن batch را دارید؛ برای دادهٔ سرد به read repair تکیه نکنید؛ جایی که هم ترمیم و هم خواندن یکنواخت می‌خواهید با QUORUM/LOCAL_QUORUM بخوانید.

read_repair_chance و حذف آن مهم ​

به زبان ساده: نسخه‌های قدیمی Cassandra می‌توانستند کسری تصادفی از خواندن‌ها را هم در پس‌زمینه repair کنند، حتی در ONE، با پرسیدن از همهٔ replicaها. این خواندن اضافه می‌خواست و هیچ تضمینی نمی‌داد، پس حذف شد.

بدفهمی رایج: «گذاشتن read_repair_chance = 1.0 جایگزین ارزان repair است.» هرگز به دادهٔ سرد نمی‌رسید، به هر خواندنی که انتخاب می‌کرد بار اضافه می‌کرد، و در Cassandra 4.0 این گزینه دیگر وجود ندارد: "Background repair has been removed. dclocal_read_repair_chance and read_repair_chance table options have been removed and are now rejected." (CASSANDRA-13910).

تعریف: در 3.x، read_repair_chance (همهٔ datacenterها) و dclocal_read_repair_chance (محلی) احتمال یک read repair پس‌زمینه و غیرمسدودکننده را تعیین می‌کردند؛ 4.0 آن‌ها را با گزینهٔ جدول read_repair (BLOCKING / NONE) جایگزین کرد.

text
     Upgrade from Cassandra 3.11 to 4.x
1    schema has WITH dclocal_read_repair_chance = 0.1
2    after upgrade, CREATE/ALTER with that option is rejected
3    remove the option from schema migration scripts; set read_repair if needed
4    replace any "background repair" assumption with scheduled repair

سناریوی واقعی: مخزن infrastructure-as-code که پس از ارتقا به Cassandra 4.0 شکست می‌خورد چون تعریف جدول‌ها هنوز read_repair_chance دارند؛ برنامهٔ ظرفیتی که روی read repair پس‌زمینه برای درست‌کردن دادهٔ سرد حساب کرده بود و حالا باید Reaper اضافه کند.

راه‌حل / نحوهٔ استفاده: گزینه‌ها را از اسکریپت‌های schema حذف کنید؛ read_repair را فقط برای انتخاب BLOCKING یا NONE به کار ببرید.

Hinted handoff و پنجرهٔ hint (Hint Window) حیاتی ​

به زبان ساده: وقتی یک replica خاموش است، coordinator نوشتن را در یک فایل «hint» محلی نگه می‌دارد و وقتی replica برگشت تحویلش می‌دهد. این کار را فقط چند ساعت انجام می‌دهد؛ بعد از آن متوقف می‌شود و replica باید با repair درست شود.

بدفهمی رایج: «با hint روشن، nodeی که برمی‌گردد سازگار است.» فقط اگر کمتر از max_hint_window خاموش بوده، فایل‌های hint روی coordinatorها سالم مانده‌اند و تحویل تمام شده است. Cassandra: "Hints are best effort, however, and do not guarantee eventual consistency like anti-entropy repair does." حذفی که در قطعی طولانی‌تر از پنجره جا افتاده دقیقاً همان حالتی است که داده را زنده می‌کند.

تعریف: بخش 4.6 در Dynamo: نوشتنی که برای node خاموش A بوده به D می‌رود با "a hint in its metadata that suggests which node was the intended recipient" و "Upon detecting that A has recovered, D will attempt to deliver the replica to A" (یک sloppy quorum). Cassandra hintها را روی دیسک coordinator نگه می‌دارد و برای میزبان مرده حداکثر به‌مدت max_hint_window (پیش‌فرض 3h) تولید می‌کند: "After it has been dead this long, new hints for it will not be created until it has been seen alive and gone down again." برای نوشتن‌هایی که timeout می‌شوند هم hint نوشته می‌شود (write_request_timeout، پیش‌فرض 2000ms). "Since hints contain the original unmodified mutation timestamp, hint application is idempotent and cannot overwrite a future mutation."

text
     t     Coordinator                          replica_2                         (CL = LOCAL_QUORUM, RF = 3)
1    t0    write to replica_1, 2, 3             restarting
2    t1    2 acks -> success to client
3    t2    write timeout (2s): store hint for replica_2 on local disk
4    t3                                         back up, gossips "alive"
5    t4    replay hints                   ->    applies the missed mutation
     ---- if replica_2 is down longer than max_hint_window (3h) ----
6          no new hints; replica_2 stays out of sync until read repair or anti-entropy repair

سناریوی واقعی: rolling restart خوشه: hintها چند دقیقه خاموشی هر node را پوشش می‌دهند؛ nodeی با دیسک خراب دو روز بیرون است: hint بعد از سه ساعت متوقف می‌شود و repair باید اجرا شود؛ hintها در قطعی طولانی روی coordinatorها انباشته می‌شوند و دیسک را پر می‌کنند (max_hints_size_per_host سقف می‌گذارد).

تنظیم (Cassandra)پیش‌فرضمعنا
hinted_handoff_enabledtrueاصلاً hint تولید شود یا نه
max_hint_window3hبرای میزبانی که بیش از این خاموش است hint نساز
hinted_handoff_throttle1024KiBبرای هر thread تحویل، به نسبت اندازهٔ خوشه کم می‌شود
max_hints_delivery_threads2برای خوشهٔ چند datacenterی بالا ببرید
max_hints_file_size128MiBاندازهٔ یک فایل hint
max_hints_size_per_host0MiB (بی‌حد)وقتی فایل‌های hint یک میزبان به این اندازه رسید، hint نساز
hinted_handoff_disabled_datacentersتنظیم‌نشدهdatacenterهایی که hint نمی‌سازند
auto_hints_cleanup_enabledfalseفایل‌های hint منقضی و یتیم را پاک کن

راه‌حل / نحوهٔ استفاده: hint را کاهش تأخیر برای قطعی‌های کوتاه بدانید. هر قطعی طولانی‌تر از max_hint_window یعنی repair همان node (nodetool repair روی آن، یا بگذارید زمان‌بند برش دارد)؛ nodetool statushandoff، getmaxhintwindow و setmaxhintwindow در زمان اجرا وضعیت را نشان و تغییر می‌دهند.

سنگ‌قبر (Tombstone / Delete Marker) حیاتی ​

به زبان ساده: به‌جای پاک‌کردن مقدار، یک رکورد کوچک بنویسید که می‌گوید «در زمان T حذف شد». این رکورد تکثیر می‌شود، repair می‌شود و درست مثل یک نوشتن عادی بر مقدارهای قدیمی‌تر غلبه می‌کند. بعداً، وقتی همهٔ replicaها حتماً دیده‌اندش، compaction هم نشانگر و هم داده‌ای را که می‌پوشاند دور می‌ریزد.

بدفهمی رایج: «tombstone فقط عادت عجیب Cassandra است.» پاسخ عمومی هر سیستمی است که replicaها یا segmentهای log در آن بعداً ادغام می‌شوند: death certificateهای Demers، tombstoneهای Cassandra و ScyllaDB، رکوردهای با مقدار null در Kafka، revisionهای _deleted در CouchDB، delete marker در SSTableهای موتورهای LSM (RocksDB، LevelDB)، و ستون‌های soft delete در جدول‌های SQL که سیستم‌های دیگر از آن‌ها همگام می‌شوند. سمت موتور ذخیره‌سازی در Storage Engines است.

تعریف: Cassandra: "Cassandra treats a deletion as an insertion, and inserts a time-stamped deletion marker called a tombstone. The tombstones go through Cassandra's write path, and are written to SSTables on one or more nodes. The key feature difference of a tombstone is that it has a built-in expiration date/time." "Once an object is marked as a tombstone, queries will ignore all values that are time-stamped previous to the tombstone insertion."

text
     Writer            n1                     n2                     n3 (down)
1    INSERT x  ->      x@10                   x@10                   x@10
2    DELETE x  ->      x@10, T@20             x@10, T@20             (missed)
3    read QUORUM n1+n2: T@20 newer than x@10 -> "no row"
4    n3 back, repair: n3 receives T@20 -> x@10 shadowed everywhere
5    after gc_grace_seconds and a compaction that includes x@10 and T@20: both removed

سناریوی واقعی: حذف ردیف‌های session یک کاربر؛ حذف سبد خرید پس از پرداخت؛ پاک‌کردن به‌خاطر GDPR در یک wide-column store (داده تا وقتی tombstone با آن compact نشود واقعاً نرفته)؛ یک جدول «صف» در Cassandra که مصرف‌کننده‌هایش ردیف‌های پردازش‌شده را حذف می‌کنند و خیلی زود از میان میلیون‌ها tombstone می‌خوانند.

موتورحذف چه می‌نویسدچه چیزی پاکش می‌کندشرط پاک‌سازی
CassandraTombstone (cell، row، range، partition)، یا انقضای TTLCompactionقدیمی‌تر از gc_grace_seconds و همهٔ SSTableهای دارای دادهٔ قدیمی‌تر آن partition در همان compaction؛ اختیاری فقط دادهٔ repaired (only_purge_repaired_tombstones)
ScyllaDBTombstoneCompactiongc_grace_seconds؛ مستندات repair در ScyllaDB: اگر زیاد حذف می‌کنید زودتر از آن repair کنید
RocksDB / LevelDB (LSM)Delete marker در memtable و SSTableها (Storage Engines را ببینید)Compactionنسخهٔ قدیمی‌تری از کلید زیر آن نمانده باشد
topic فشرده‌شده در Kafkaرکورد با key و مقدار nullLog cleanerپس از delete.retention.ms
CouchDBrevision تازه با _deleted: true_purgeدرخواست صریح
soft delete در PostgreSQLdeleted_at مقدار می‌گیردDELETE زمان‌بندی‌شدهٔ شماسیاست نگهداری شما

راه‌حل / نحوهٔ استفاده: هر جا replicaها، کش‌ها یا کلاینت‌ها بعداً وضعیت را ادغام می‌کنند، حذف را نوشتن مدل کنید و به هر نشانگر عمری آگاهانه بدهید که از طولانی‌ترین زمانی که هر replica یا مصرف‌کننده ممکن است بی‌خبر بماند بیشتر باشد.

زنده‌شدن داده (Resurrection)، داده‌ٔ زامبی (Zombie Data) و gc_grace_seconds حیاتی ​

به زبان ساده: اگر tombstone پیش از رسیدن به همهٔ replicaها پاک شود، replicaای که هرگز حذف را ندیده هنوز مقدار قدیمی را دارد و repair یا خواندن بعدی آن را برمی‌گرداند. دادهٔ حذف‌شده دوباره زنده است: یک زامبی.

بدفهمی رایج: «gc_grace_seconds تنظیم کارایی است؛ کمش کنید تا tombstoneها زودتر بروند.» این یک قرارداد درستی است: بیشترین زمانی است که بین یک حذف و لحظه‌ای که همهٔ replicaها آن را دارند مجاز می‌دانید. "If a node remains down or disconnected for longer than gc_grace_seconds, its deleted data will be repaired back to the other nodes and reappear in the cluster."

تعریف: Cassandra: "If the tombstoned object has already been deleted from the rest of the cluster before that node recovers, Cassandra treats the object on the recovered node as new data, and propagates it to the rest of the cluster. This kind of deleted but persistent object is called a zombie." "To prevent the reappearance of zombies, Cassandra gives each tombstone a grace period. The grace period for a tombstone is set with the table property WITH gc_grace_seconds. Its default value is 864000 seconds (ten days)". قاعده‌ای که نتیجه می‌شود: repair همهٔ replicaها را درون gc_grace_seconds تمام کنید. cassandra.yaml (5.0) یک وارسی اختیاری هنگام راه‌اندازی دارد، check_data_resurrection، "to fail startup if the node is down for longer than gc_grace_seconds".

Why deletes need tombstones, and why tombstones need repair within gc_grace_seconds1. write x (RF=3)2. DELETE x, n3 down3. later4. n3 back, repairxxx--x--xxxxn1n2n3zombie: x is backxxxx+Tx+Txx+Tx+Txx+Tx+Tx+Tn1n2n3stays deletedxxxx+Tx+Tx--xxxxn1n2n3zombie: x is backHard deleteTombstone, repairedwithin gc_graceTombstone purgedcompacted after gc_gracex+T = row plus a newer tombstone (the tombstone wins). Dashed = replica down. Cassandra defaultgc_grace_seconds = 864000 (10 days); repair every node within that window.
text
     Day   n1, n2                                 n3                         gc_grace_seconds = 1 day
1    0     x                                      x
2    0     (n3 goes down)                         down
3    0.2   DELETE x -> T                          misses it; down > max_hint_window, no hint
4    1.2   compaction: T older than grace -> x and T purged
5    2.2   n3 back: still has x
6    2.2   repair: n1, n2 have nothing, n3 has x -> x streamed back: zombie

سه ردیف تصویر همان سه حالت مستندات Cassandra است: حذف سخت که با repair برمی‌گردد؛ tombstone که به‌موقع repair شده و حذف می‌ماند؛ و tombstone که پیش از repair با compaction پاک شده و زامبی می‌سازد.

سناریوی واقعی: سبد خریدی که هنگام پرداخت خالی شده یک هفته بعد، پس از بازسازی یک node از snapshot قدیمی، دوباره پیدا می‌شود؛ ردیف یک مجوز لغوشده برمی‌گردد؛ کاربرانی که لغو اشتراک کرده‌اند دوباره ایمیل می‌گیرند؛ تیمی که برای رفع هشدار tombstone مقدار gc_grace_seconds یک جدول را یک ساعت کرد و بعد قطعی دوساعتهٔ یک node داده را زنده کرد.

راه‌حل / نحوهٔ استفاده: gc_grace_seconds را بزرگ‌تر از چرخهٔ repair به‌اضافهٔ حاشیه نگه دارید؛ هر nodeی را که بیش از max_hint_window خاموش بوده repair کنید؛ nodeی را که بیش از gc_grace_seconds بیرون بوده هرگز بدون پاک‌کردن و بازسازی برنگردانید (یا check_data_resurrection را روشن کنید)؛ روی جدول‌هایی که فقط دادهٔ TTLدار، هرگز حذف‌نشده و هرگز به‌روزنشده دارند، grace کمتر امن است چون هر replica داده را مستقل منقضی می‌کند.

سربار tombstone، هشدار و شکست مهم ​

به زبان ساده: یک خواندن باید از روی همهٔ tombstoneهای بین ردیف‌هایی که می‌خواهد بگذرد و آن‌ها را به coordinator برگرداند تا replicaهای دیگر از حذف‌ها باخبر شوند. partitionی با صد هزار tombstone یک SELECT ساده را کند می‌کند، heap مصرف می‌کند و در نهایت شکست می‌خورد.

بدفهمی رایج: «اگر ردیف حذف کنم خواندن سریع‌تر می‌شود.» تا وقتی compaction tombstoneها را پاک نکرده، برعکس است: ردیف‌ها هنوز هستند و نشانگرها هم اضافه شده‌اند. توضیح cassandra.yaml دقیقاً به همین دلیل به "cassandra-anti-patterns-queues-and-queue-like-datasets" ارجاع می‌دهد.

تعریف: "When executing a scan, within or across a partition, we need to keep the tombstones seen in memory so we can return them to the coordinator, which will use them to make sure other replicas also know about the deleted rows. With workloads that generate a lot of tombstones, this can cause performance problems and even exhaust the server heap." tombstone_warn_threshold (پیش‌فرض 1000) هشدار در log می‌نویسد؛ tombstone_failure_threshold (پیش‌فرض 100000) کوئری را با TombstoneOverwhelmingException متوقف می‌کند. guardrailهای partition_tombstones_warn_threshold / partition_tombstones_fail_threshold (پیش‌فرض -1، خاموش) partitionها را هنگام نوشتن SSTable بررسی می‌کنند.

text
     Queue-like table: messages(queue_id, msg_id) consumed and deleted
1    producer inserts 200000 messages into partition q1
2    consumers delete each message after processing -> 200000 row tombstones in q1
3    SELECT * FROM messages WHERE queue_id = 'q1' LIMIT 10
4    replica scans tombstones before finding 10 live rows
5    > 1000:   WARN  Read 10 live rows and 1500 tombstone cells for query ...; token ... (see tombstone_warn_threshold)
6    > 100000: Scanned over 100001 tombstones during query '...' (last scanned row token was ... and partion key was (...)); query aborted

سناریوی واقعی: صف کار یا «صندوق ورودی» که به شکل یک partition در Cassandra مدل شده؛ partition مرتب‌شده بر زمان که ردیف‌های قدیمی از جلویش حذف می‌شوند، پس هر خواندن جدیدترین ردیف‌ها با دیواری از tombstone شروع می‌شود؛ ستون‌های مجموعه‌ای (set، map) که یکجا بازنویسی می‌شوند و هر بار برای مجموعهٔ قبلی tombstone می‌نویسند.

راه‌حل / نحوهٔ استفاده: صف را در Cassandra مدل نکنید (از broker استفاده کنید، Messaging Fundamentals)؛ در partition key سطل زمانی بگذارید و کل سطل را حذف کنید (یک partition tombstone، یا TTL با Time Window Compaction Strategy)؛ با بازهٔ clustering بخوانید که بعد از ناحیهٔ حذف‌شده شروع شود؛ TombstoneScannedHistogram را پایش کنید؛ بالا بردن آستانهٔ شکست راه‌حل نیست.

انواع tombstone: cell، row، range، partition، TTL مهم ​

به زبان ساده: اندازهٔ نشانگر به چیزی بستگی دارد که حذف کرده‌اید. مقدار یک ستون، یک ردیف، برشی از ردیف‌ها در یک partition، کل یک partition، یا داده‌ای که فقط منقضی شده (TTL) هرکدام نوع دیگری از نشانگر به جا می‌گذارند؛ یک نشانگر می‌تواند میلیون‌ها ردیف را بپوشاند و یک نشانگر برای هر ردیف می‌تواند یک partition را دفن کند.

بدفهمی رایج: «TTL جلوی tombstone را می‌گیرد.» دادهٔ منقضی به tombstone تبدیل می‌شود (TTL Tombstone): "After this amount of time has ended, Cassandra marks the object with a tombstone, and handles it like other tombstoned objects." TTL رفت‌وبرگشت حذف را حذف می‌کند، نه نشانگر را.

تعریف: در CQL کاساندرا: "A range of rows may be deleted using an inequality operator (such as >= )" که یک range tombstone برای کل برش می‌نویسد؛ DELETE FROM t WHERE pk = ? یک partition tombstone می‌نویسد؛ حذف یک ستون یک cell tombstone. پاک‌سازی در compaction رخ می‌دهد: "a tombstone can live in one SSTable and the data it marks for deletion in another, so a compaction must also remove both SSTables." SSTableی که فقط دادهٔ منقضی دارد می‌تواند یکجا دور ریخته شود («Fully expired SSTables») و sstableexpiredblockers نشان می‌دهد چه چیزی مانعش است.

text
     Statement                                                     Marker written
1    DELETE email FROM users WHERE id = 7                           cell tombstone
2    DELETE FROM events WHERE day = '2026-11-01' AND ts = t1        row tombstone
3    DELETE FROM events WHERE day = '2026-11-01' AND ts < t2        range tombstone (one marker for a slice)
4    DELETE FROM events WHERE day = '2026-11-01'                    partition tombstone
5    INSERT ... USING TTL 86400                                     cell expires after a day -> treated as a tombstone

سناریوی واقعی: event storeی با کلید روز که کل روزها را با یک partition tombstone حذف می‌کند؛ کار نگهداری که «قدیمی‌تر از ۳۰ روز» را درون partition هر دستگاه با یک range tombstone حذف می‌کند به‌جای یک میلیون row tombstone؛ دادهٔ session که با TTL نوشته و با Time Window Compaction Strategy فشرده می‌شود و هنگام انقضا کل SSTableها را دور می‌ریزد.

گزینهٔ compaction (Cassandra)پیش‌فرضکاربرد
tombstone_threshold0.2compaction تک‌SSTable وقتی این کسر tombstone است
tombstone_compaction_interval86400sکمترین فاصلهٔ بین چنین تلاش‌هایی برای هر SSTable
unchecked_tombstone_compactionfalseپیش‌وارسی‌های هم‌پوشانی را رد می‌کند؛ باز هم فقط tombstoneهای امن را پاک می‌کند
only_purge_repaired_tombstonesfalsetombstone را فقط از دادهٔ repaired پاک کن

راه‌حل / نحوهٔ استفاده: در درشت‌ترین سطحی که مدل اجازه می‌دهد حذف کنید (partition، بعد range، بعد row)؛ برای داده‌ای که با سن منقضی می‌شود TTL و TWCS؛ اگر می‌خواهید SSTableها یکجا منقضی شوند، دادهٔ TTLدار و بی‌TTL را در یک partition مخلوط نکنید ("Cassandra will have a hard time dropping the tombstones").

Tombstone در logها: Kafka compaction، delete.retention.ms، Redis Streams مهم ​

به زبان ساده: یک topic فشرده‌شده در Kafka آخرین مقدار هر key را نگه می‌دارد. برای حذف یک key، همان key را با مقدار خالی (null) می‌نویسید. مصرف‌کننده‌هایی که topic را از ابتدا می‌خوانند delete marker را می‌بینند، به شرطی که پیش از پاک‌شدنش توسط cleaner به آن برسند.

بدفهمی رایج: «نوشتن مقدار null کلید را فوراً برای همه حذف می‌کند.» نشانگر (Kafka Tombstone) مقدارهای قدیمی‌تر را در compaction پاک می‌کند و خودش پس از delete.retention.ms پاک می‌شود. مصرف‌کننده‌ای که وضعیت را از offset 0 بازسازی می‌کند و کندتر از این است، حذف را از دست می‌دهد و key را برای همیشه نگه می‌دارد. این همان زامبی Cassandra در یک log است.

تعریف: طراحی Kafka: "A message with a key and a null payload will be treated as a delete from the log. Such a record is sometimes referred to as a tombstone." "all delete markers for deleted records will be seen, provided the consumer reaches the head of the log in a time period less than the topic's delete.retention.ms setting (the default is 24 hours)." delete.retention.ms (topic) / log.cleaner.delete.retention.ms (پیش‌فرض broker) برابر 86400000 است. min.compaction.lag.ms رکوردهای تازه را دست‌کم همین‌قدر فشرده‌نشده نگه می‌دارد. Redis Streams برای مصرف‌کننده‌ها delete marker تکثیرشده ندارد: XDEL یک ورودی را از stream برمی‌دارد و در درون "the entry is not really evicted, it just gets marked as deleted" تا وقتی کل macro node آن خالی شود.

text
     Producer                         Compacted topic users (cleanup.policy=compact)      Slow consumer
1    key=u7 value={...}         ->    offset 10: u7 -> {...}
2    key=u7 value=null          ->    offset 11: u7 -> null (tombstone)
3                                     cleaner: drops offset 10
4                                     24h later (delete.retention.ms): drops offset 11
5                                                                                         restarts from offset 0 after 30h
6                                                                                         never sees u7 at all: fine
     ---- but if the consumer read offset 10 before step 3 and reached offset 11 after step 4: it keeps u7 forever

سناریوی واقعی: topic تغییرات پروفایل کاربر که برای بازسازی کش به کار می‌رود؛ خط لولهٔ CDC که حذف ردیف‌ها را به tombstone روی یک topic فشرده‌شده تبدیل می‌کند (Change Data Capture را ببینید)؛ نمای مادی‌شده به سبک KTable؛ read model در event sourcing (Event Sourcing & CQRS).

راه‌حل / نحوهٔ استفاده: delete.retention.ms را بلندتر از طولانی‌ترین بازپخش کاملی که هر مصرف‌کننده انجام می‌دهد بگذارید؛ وقتی lag مصرف‌کننده به آن نزدیک شد هشدار دهید؛ در Go با franz-go یک tombstone رکوردی با Value: nil است؛ مقدار null را روی topicهای فشرده‌شده فقط برای حذف به کار ببرید.

حذف نرم (Soft Delete) در برابر tombstone (SQL، SoftDeletes، Prunable) حیاتی ​

به زبان ساده: soft delete ردیف را نگه می‌دارد و deleted_at را مقدار می‌دهد. درون یک دیتابیس SQL این یک قابلیت UX است (undo، سطل زباله، audit). به‌محض این‌که سیستم‌های دیگر آن جدول را کپی کنند (کلاینت موبایل، search index، کش، انبار داده)، ردیف soft-deleted همان tombstoneی هم هست که به آن‌ها می‌گوید کپی‌شان را حذف کنند، و هرس‌کردن (Pruning) آن یعنی garbage collection با همان قاعدهٔ دورهٔ مهلت.

بدفهمی رایج: «soft delete برای undo است؛ همگام‌سازی می‌تواند از updated_at > ? استفاده کند.» ردیفی که hard delete شده هرگز در هیچ کوئری «تغییرکرده از» ظاهر نمی‌شود، پس هر کپی پایین‌دستی نگهش می‌دارد. و «ردیف‌های soft-deleted را بعد از ۷ روز prune کن» بی‌صدا به باگ زنده‌شدن برای گوشی‌ای تبدیل می‌شود که ۸ روز آفلاین بوده.

تعریف: Laravel: "When models are soft deleted, they are not actually removed from your database. Instead, a deleted_at attribute is set on the model". کوئری‌ها به‌طور خودکار آن‌ها را کنار می‌گذارند؛ withTrashed() و onlyTrashed() آن‌ها را می‌آورند؛ restore() برمی‌گرداند؛ forceDelete() برای همیشه پاک می‌کند. Pruning: Prunable یا MassPrunable را اضافه کنید، ردیف‌های منقضی را از prunable() برگردانید و model:prune را زمان‌بندی کنید؛ "Soft deleting models will be permanently deleted (forceDelete) if they match the prunable query." MassPrunable با یک کوئری حذف می‌کند، پس "the pruning method will not be invoked, nor will the deleting and deleted model events be dispatched."

text
     Server (Laravel)                            Phone (offline 3 days)
1    doc 9 exists                                doc 9 cached
2    DELETE /docs/9 -> deleted_at = now()        (offline)
3    sync diff for other clients includes {id: 9, deleted: true}
4    day 30: model:prune force-deletes doc 9 (grace = 30 days)
5                                                day 3: online, last_synced_at 3 days ago < 30 days
6                                                bucket of doc 9 differs -> receives {id: 9, deleted: true} -> drops it
     ---- a phone offline 40 days gets 409 resync_required instead of a silent zombie

سناریوی واقعی: یادداشت‌های موبایل آفلاین‌محور؛ search indexی که با polling «تغییرکرده از» تغذیه می‌شود؛ انبار داده‌ای که هر شب deltaها را می‌خواند؛ SaaS چندمستأجری با سطل بازیافت؛ درخواست‌های حق پاک‌شدن که باید سرانجام ردیف را واقعاً حذف کنند.

رویکردحذف برای کلاینت همگام‌ساز دیده می‌شود؟فضاUndoپاک‌سازی (Erasure)
DELETE سختنههمین حالا آزادنداردفوری در primary، نه در کپی‌ها
Soft delete بی pruneبلههمیشه رشد می‌کندداردهرگز، مگر ستون‌ها را خالی کنید
Soft delete + prune پس از دورهٔ مهلتبله، درون دورهٔ مهلتمحدوددرون مهلتپس از مهلت، به‌اضافهٔ resync کپی‌ها
جدول tombstone جدا (id، deleted_at) + hard delete ردیفبله، درون نگهداری tombstoneکوچکنداردpayload فوراً حذف؛ id تا prune می‌ماند
log رویداد حذف (outbox / CDC)بله، برای مصرف‌کننده‌های درون retentionretention آن logنداردبه log بستگی دارد (compaction)

راه‌حل / نحوهٔ استفاده: در SQL، یک partial index روی ردیف‌های زنده و prune دسته‌ای؛ در Laravel، SoftDeletes به‌اضافهٔ Prunable با دورهٔ مهلتی بلندتر از طولانی‌ترین زمان آفلاین پشتیبانی‌شده، و API همگام‌سازی که ردیف‌های trashed را شامل می‌شود و کلاینت‌های قدیمی‌تر از دورهٔ مهلت را رد می‌کند. هر دو در حل مسئله‌های کلاسیک و Laravel آمده‌اند.

پروتکل‌های همگام‌سازی کلاینت: CouchDB replication، همگام‌سازی مرکلی، rsync مهم ​

به زبان ساده: سه خانواده برای «به‌روز کردن طرف مقابل» داریم: دنبال‌کردن log تغییرات از یک checkpoint (CouchDB)، مقایسهٔ هش bucketها و گرفتن bucketهای متفاوت (همگام‌سازی مرکلی)، یا مقایسهٔ checksum بلاک‌های یک فایل و فرستادن فقط بلاک‌های جورنشده (rsync).

بدفهمی رایج: «CouchDB replication از درخت مرکل استفاده می‌کند.» پروتکل یک changes feed به‌اضافهٔ checkpoint است: replicator از GET /{db}/_changes?since=... می‌خواند، با POST /{db}/_revs_diff از مقصد می‌پرسد کدام revisionها را ندارد و checkpointها را در یک replication log ثبت می‌کند. حذف‌ها به شکل revision با "deleted": true جابه‌جا می‌شوند؛ "Normal deletion of a document within CouchDB does not remove the document from the database, instead, the document is marked as _deleted=true (and a new revision is created). This is to ensure that deleted documents can be replicated to other databases as having been deleted."

تعریف: changes feed وقتی ارزان است که کلاینت اخیراً آنلاین بوده و سرور تاریخچه نگه می‌دارد؛ مقایسهٔ مرکلی وقتی ارزان است که کلاینت ممکن است هر قدر کهنه باشد یا سرور log نگه ندارد، و هزینه‌اش به تعداد تفاوت‌ها بستگی دارد؛ «weak rolling checksum» در rsync را می‌توان "for blocks of length S at all possible offsets within a file in a "rolling" fashion, with very little computation at each point" حساب کرد، پس دادهٔ جابه‌جاشده درون یک فایل را پیدا می‌کند.

text
     CouchDB replication (changes feed)                 Merkle sync endpoint (this page's Laravel code)
1    GET target/_local/<replication id> -> checkpoint     GET /sync/root -> root R
2    GET source/_changes?since=seq                       client root == R ? done
3    POST target/_revs_diff {id: [revs]}                 POST /sync/diff {256 bucket hashes, last_synced_at}
4    fetch missing revisions, write to target            server returns rows of divergent buckets (incl. deleted)
5    PUT checkpoint                                      client applies, recomputes its buckets

سناریوی واقعی: PouchDB در مرورگر که با CouchDB همگام می‌شود؛ اپ خدمات میدانی که دستورکارها را روی لینک موبایل بد همگام می‌کند؛ همگام‌سازی بلاکی فایل‌های بزرگ به سبک Dropbox (استنباط: هش بلاک برای حذف تکرار الگوی رایج است؛ توضیح خود Dropbox را نخوانده‌ایم)؛ rsync -a یک درخت پوشه بین سرورها.

پروتکلتفاوت‌ها را چطور پیدا می‌کندهزینه وقتی هم‌گام‌اندهزینه پس از آفلاین طولانیحذف‌ها
CouchDB replicationchanges feed از یک checkpointیک درخواست changes خالیهمهٔ تغییرات از checkpointrevisionهای _deleted؛ _purge پاکشان می‌کند
همگام‌سازی مرکلی (bucket)ریشه، بعد هش bucketهایک root hashهش‌ها به‌اضافهٔ ردیف‌های bucketهای واگراtombstoneها باید در ردیف‌های هش‌شده باشند
rsyncchecksum بلاک + rolling checksumchecksum همهٔ بلاک‌هابلاک‌های جورنشدهفایل: --delete روی گیرنده
polling با «updated_at > since»ستون timestampیک کوئریهمهٔ ردیف‌های تغییرکرده از آن زماننامرئی، مگر soft-deleted باشند

راه‌حل / نحوهٔ استفاده: اگر log تغییرات ماندگار با retention طولانی دارید، changes feed ساده‌ترین است. اگر کلاینت‌ها می‌توانند هفته‌ها کهنه باشند و نمی‌توانید log را برای همیشه نگه دارید، bucketهای مرکلی را به کار ببرید، tombstoneها را در هش بگنجانید و دوره‌ای تعریف کنید که پس از آن کلاینت باید resync کند.

Observability: تأخیر repair، شمار tombstone، hintها مهم ​

به زبان ساده: خرابی این فصل تا وقتی یک ردیف حذف‌شده برنگشته بی‌صداست. تنها دفاع، نموداری از «از آخرین full repair هر جدول چقدر گذشته» کنار gc_grace_seconds است، به‌اضافهٔ شمارنده‌هایی برای tombstoneهای خوانده‌شده و hintهای گیرکرده.

بدفهمی رایج: «اگر nodetool repair هفتهٔ پیش با کد 0 تمام شد، مشکلی نداریم.» repair یک node کل خوشه را پوشش نمی‌دهد؛ زمان‌بند می‌تواند جدول‌هایی را جا بیندازد؛ incremental repair می‌تواند مجموعهٔ repaired را ماه‌ها بی‌بررسی بگذارد. برای هر جدول و هر بازه اندازه بگیرید.

تعریف: معیارهای جدول در Cassandra شامل PercentRepaired، BytesRepaired، BytesUnrepaired، BytesPendingRepair، TombstoneScannedHistogram، TombstoneWarnings و TombstoneFailures است؛ زمان‌سنج‌های repair شامل ValidationTime ("Time spent doing validation compaction during repair")، SyncTime و RepairTime؛ برای hint معیار Hints_created-<PeerIP> و meterهای HintsService یعنی HintsSucceeded، HintsFailed، HintsTimedOut هست. read repair رویدادهای تشخیصی دارد (endpointهای تماس‌گرفته، پاسخ‌های digest، partition keyهای متأثر).

text
     Alert rules (expected configuration)
1    time_since_last_full_repair(table) > gc_grace_seconds - 3 days        -> page
2    PercentRepaired(table) < 80 for 2 days (incremental users)            -> ticket
3    rate(TombstoneWarnings) > 0 for 15 min                                -> ticket: data model
4    HintsTimedOut or hints on disk growing for 1 hour                     -> check the target node
5    node down > max_hint_window                                           -> schedule repair of that node

سناریوی واقعی: داشبوردی برای هر keyspace که سن repair را به روز با خط قرمز روی gc_grace_seconds نشان می‌دهد؛ histogram tombstone که آن یک جدول مدل‌شده به شکل صف را پیدا می‌کند؛ انباشت hint که nodeی را نشان می‌دهد که بالا هست ولی نوشتن نمی‌پذیرد.

راه‌حل / نحوهٔ استفاده: این معیارها را صادر کنید (JMX exporter یا virtual tableهای Cassandra)، تاریخچهٔ repair را در Reaper یا system_distributed.auto_repair_history نگه دارید، و دورهٔ مهلت را روی همان نمودار سن repair بگذارید.

سازوکار (Mechanics) ​

اندازهٔ اثبات‌ها و حساب diff ​

کمیتفرمولمثال
طول inclusion proof (دودویی، RFC 6962)حداکثر ceil(log2 n) هشn = 1,000,000: ۲۰ هش، ۶۴۰ بایت با SHA-256
طول consistency proofحداکثر ceil(log2 n) + 1از 600,000 به 1,000,000: ۱۵ هش (آزمایشگاه)
diff دو درخت یکسان۱ مقایسههر اندازه‌ای
diff با k برگ واگرا، fan-out b، عمق dحداکثر 1 + k * b * d مقایسه، d + 1 دورk = 1، b = 16، d = 4: ۶۵ هش، ۵ دور
داده‌ٔ stream‌شده برای هر برگ واگراحدود n / b^d کلید100,000 کلید، ۱۶ برگ: حدود ۶۰۰۰ کلید برای یک تغییر
مقایسهٔ کل داده بدون درختn کلید (یا هش) در هر دو جهت100,000 کلید: 200,000 ورودی فرستاده می‌شود (کد Before)
حافظهٔ درختb^d هش برگ (+ گره‌های داخلی، حدود 1/(b-1) بیشتر)65,536 برگ × ۳۲ بایت = ۲ مگابایت

عدم‌تقارن مهم این است: ساختن درخت همیشه همهٔ دادهٔ بازه را می‌خواند (Cassandra این را با نام validation compaction زمان‌سنجی می‌کند)، اما هزینهٔ شبکه متناسب با تفاوت‌هاست. برای همین repair سنگینِ دیسک است و برای همین Riak درخت‌ها را ماندگار نگه می‌دارد و با هر نوشتن به‌روز می‌کند.

تنظیم‌ها، محصول به محصول ​

محصولتنظیمپیش‌فرضچه چیزی را کنترل می‌کند
جدول Cassandragc_grace_seconds864000tombstone چقدر بماند تا compaction بتواند پاکش کند
جدول Cassandraread_repairBLOCKINGNONE خواندن را آشتی می‌دهد بی‌آن‌که برنویسد
جدول Cassandradefault_time_to_live0TTL برای ردیف‌های بدون USING TTL صریح
yaml در Cassandramax_hint_window3hتولید hint برای هر میزبان خاموش
yaml در Cassandratombstone_warn_threshold / tombstone_failure_threshold1000 / 100000حد اسکن tombstone در هر کوئری
yaml در Cassandrarepair_session_space۱/۱۶ heapحافظهٔ درخت مرکل، پس وضوح
yaml در Cassandraconcurrent_merkle_tree_requests0 (بی‌حد)ساخت هم‌زمان درخت در هر فرمان repair
compaction در Cassandraonly_purge_repaired_tombstonesfalsetombstone فقط از دادهٔ repaired پاک شود
وارسی راه‌اندازی Cassandracheck_data_resurrectionخاموشپس از خاموشی طولانی‌تر از gc_grace_seconds راه نیفتد
topic در Kafkacleanup.policy=compact، delete.retention.ms86400000tombstone چقدر در topic فشرده‌شده بماند
topic در Kafkamin.compaction.lag.ms / max.compaction.lag.ms0 / 9223372036854775807 (Long.MAX)پنجرهٔ پیش از این‌که رکورد قابل compaction شود
Riak KVAAEروشنتبادل درخت در پس‌زمینه؛ ساخت دوبارهٔ هفتگی درخت‌ها
Laravelprunable() + زمان‌بندی model:pruneنداردکدام ردیف‌های soft-deleted و چه زمانی forceDelete شوند

پیام‌های خطا و خط‌های log که واقعاً می‌بینید ​

پیاممنبعمعنااقدام
Scanned over %d tombstones during query '%s' (last scanned row token was %s and partion key was (%s)); query abortedTombstoneOverwhelmingException در Cassandraاز tombstone_failure_threshold گذشتهمدل داده را درست کنید؛ compact کنید؛ بالا بردن آستانه راه‌حل نیست
Read %d live rows and %d tombstone cells for query %1.512s; token %s (see tombstone_warn_threshold)هشدار ReadCommand در Cassandraبالاتر از tombstone_warn_thresholdجدول را با TombstoneScannedHistogram پیدا کنید
When increasing replication factor you need to run a full (-full) repair to distribute the data.هشدار cqlsh روی ALTER KEYSPACEreplicaهای تازه خالی‌اندnodetool repair -full روی keyspace
Repair completed successfully / Repair command #1 finished in 1 secondnodetool repairبازه‌های این node repair شدندبرای هر جدول ثبت کنید؛ روی همهٔ nodeها تکرار کنید (-pr)
گزینهٔ جدول read_repair_chance رد می‌شودschema در Cassandra 4.0 به بعدگزینه حذف شده (CASSANDRA-13910)از migrationها حذفش کنید
409 {"resync_required": true}API همگام‌سازی Laravel همین صفحهکلاینت قدیمی‌تر از دورهٔ مهلت tombstone استکپی را پاک و نسخهٔ تازه دانلود کنید

Go ​

ماژول academy/merkle-trees-anti-entropy فقط از کتابخانهٔ استاندارد استفاده می‌کند. merkle درخت RFC 6962 با inclusion proof و consistency proof و diff درخت است، antientropy درخت بازه‌ای با شکل ثابت است که replicaها مقایسه می‌کنند، kvsim یک store سه‌replicaی بی‌رهبر با hint، read repair، ترمیم مرکلی و دو حالت حذف است، و cmd/aesim خروجی آزمایشگاه را چاپ می‌کند.

Before ​

همگام‌سازی replica همان‌طور که معمولاً اول نوشته می‌شود: برای مقایسه هر کلید را بفرست، برای حذف ردیف را بردار. تست‌ها هر دو شکست را ثبت می‌کنند: ۲۰٬۰۰۰ ورودی برای دو replica یکسانِ ۱۰٬۰۰۰ کلیدی، و سبد حذف‌شده‌ای که همگام‌سازی برش می‌گرداند.

go
// Package before is the replica sync most teams write first: compare by
// shipping every key, delete by removing the local row. Both are correct on
// a single machine and both break between replicas.
package before

// Store is one replica: key -> value, no timestamps, no delete markers.
type Store map[string]string

// FullSync merges two replicas by sending every entry in both directions.
// It returns the number of entries that crossed the network, which is the
// size of the dataset even when the replicas are already identical.
func FullSync(a, b Store) (sent int) {
	for k, v := range a {
		if _, ok := b[k]; !ok {
			b[k] = v
		}
		sent++
	}
	for k, v := range b {
		if _, ok := a[k]; !ok {
			a[k] = v
		}
		sent++
	}
	return sent
}

// Delete removes the row locally. A replica that missed this call still has
// the row, and FullSync cannot tell "deleted here" from "never written here".
func Delete(s Store, key string) { delete(s, key) }
go
package before

import (
	"fmt"
	"testing"
)

func TestFullSyncCostsTheWholeDataset(t *testing.T) {
	a, b := Store{}, Store{}
	for i := 0; i < 10000; i++ {
		k := fmt.Sprintf("user:%d", i)
		a[k], b[k] = "v1", "v1"
	}
	if sent := FullSync(a, b); sent != 20000 {
		t.Fatalf("sent %d entries for two identical replicas", sent)
	}
}

func TestHardDeleteComesBack(t *testing.T) {
	a, b := Store{"cart:42": "3 items"}, Store{"cart:42": "3 items"}
	Delete(a, "cart:42") // b was unreachable and missed the delete
	FullSync(a, b)
	if _, ok := a["cart:42"]; !ok {
		t.Fatal("expected the deleted row to be resurrected (this is the bug)")
	}
}

After ​

درخت مرکل RFC 6962. هش برگ و گره با پیشوندهای 0x00/0x01، ریشهٔ هر پیشوند از log (RootAt)، audit path، consistency proof، الگوریتم‌های وارسی RFC 9162، و Diff که فقط به زیردرخت‌هایی با هش متفاوت پایین می‌رود:

go
// Package merkle implements the Merkle Tree Hash of RFC 6962 / RFC 9162:
// leaves are hashed as SHA-256(0x00 || data), inner nodes as
// SHA-256(0x01 || left || right), and an n-leaf list is split at the largest
// power of two smaller than n. It provides inclusion (audit) proofs,
// consistency proofs between two tree sizes, and a structural diff that
// descends only into subtrees whose hashes differ.
//
// A Tree is not safe for concurrent use: subtree hashes are memoised.
package merkle

import (
	"bytes"
	"crypto/sha256"
	"errors"
)

// Domain-separation prefixes from RFC 6962 section 2.1. Without them a leaf
// could be passed off as an inner node (second preimage attack).
const (
	leafPrefix byte = 0x00
	nodePrefix byte = 0x01
)

var (
	// ErrIndex is returned for a leaf index or tree size outside the tree.
	ErrIndex = errors.New("merkle: index out of range")
	// ErrShape is returned by Diff when the trees have different sizes.
	ErrShape = errors.New("merkle: trees have different sizes")
)

// LeafHash returns SHA-256(0x00 || data).
func LeafHash(data []byte) []byte {
	h := sha256.New()
	h.Write([]byte{leafPrefix})
	h.Write(data)
	return h.Sum(nil)
}

// NodeHash returns SHA-256(0x01 || left || right).
func NodeHash(left, right []byte) []byte {
	h := sha256.New()
	h.Write([]byte{nodePrefix})
	h.Write(left)
	h.Write(right)
	return h.Sum(nil)
}

// Tree is an append-only list of leaf hashes plus a memo of subtree hashes.
type Tree struct {
	leaves [][]byte
	memo   map[[2]int][]byte
}

// New hashes every data item into a leaf.
func New(data [][]byte) *Tree {
	t := &Tree{memo: map[[2]int][]byte{}}
	for _, d := range data {
		t.Append(d)
	}
	return t
}

// Append adds one data item as the next leaf. Earlier subtree hashes stay
// valid because a subtree never changes once all its leaves exist.
func (t *Tree) Append(data []byte) {
	t.leaves = append(t.leaves, LeafHash(data))
}

// Size is the number of leaves.
func (t *Tree) Size() int { return len(t.leaves) }

// Root is the Merkle Tree Hash of all leaves (the root hash).
func (t *Tree) Root() []byte { return t.mth(0, len(t.leaves)) }

// RootAt is the root hash of the first size leaves, as a log would have
// published it when it had size entries.
func (t *Tree) RootAt(size int) ([]byte, error) {
	if size < 0 || size > len(t.leaves) {
		return nil, ErrIndex
	}
	return t.mth(0, size), nil
}

// split returns the largest power of two strictly smaller than n (n > 1).
func split(n int) int {
	k := 1
	for k<<1 < n {
		k <<= 1
	}
	return k
}

// mth is MTH(D[lo:hi]).
func (t *Tree) mth(lo, hi int) []byte {
	switch hi - lo {
	case 0:
		s := sha256.Sum256(nil)
		return s[:]
	case 1:
		return t.leaves[lo]
	}
	key := [2]int{lo, hi}
	if h, ok := t.memo[key]; ok {
		return h
	}
	k := split(hi - lo)
	h := NodeHash(t.mth(lo, lo+k), t.mth(lo+k, hi))
	t.memo[key] = h
	return h
}

// InclusionProof returns the audit path for leaf index in the tree of the
// first size leaves: the sibling hashes from the leaf up to the root.
func (t *Tree) InclusionProof(index, size int) ([][]byte, error) {
	if size > len(t.leaves) || index < 0 || index >= size {
		return nil, ErrIndex
	}
	return t.path(index, 0, size), nil
}

func (t *Tree) path(m, lo, hi int) [][]byte {
	if hi-lo <= 1 {
		return nil
	}
	k := split(hi - lo)
	if m < k {
		return append(t.path(m, lo, lo+k), t.mth(lo+k, hi))
	}
	return append(t.path(m-k, lo+k, hi), t.mth(lo, lo+k))
}

// VerifyInclusion checks an audit path with the algorithm of RFC 9162
// section 2.1.3.2. leafHash is LeafHash(data), not the data itself.
func VerifyInclusion(leafHash []byte, index, size int, proof [][]byte, root []byte) bool {
	if index < 0 || index >= size {
		return false
	}
	fn, sn := index, size-1
	r := leafHash
	for _, p := range proof {
		if sn == 0 {
			return false
		}
		if fn&1 == 1 || fn == sn {
			r = NodeHash(p, r)
			for fn&1 == 0 && fn != 0 {
				fn >>= 1
				sn >>= 1
			}
		} else {
			r = NodeHash(r, p)
		}
		fn >>= 1
		sn >>= 1
	}
	return sn == 0 && bytes.Equal(r, root)
}

// ConsistencyProof proves that the tree of the first `first` leaves is a
// prefix of the tree of the first `second` leaves (RFC 6962 PROOF(m, D[n])).
func (t *Tree) ConsistencyProof(first, second int) ([][]byte, error) {
	if second > len(t.leaves) || first <= 0 || first > second {
		return nil, ErrIndex
	}
	if first == second {
		return nil, nil
	}
	return t.subproof(first, 0, second, true), nil
}

func (t *Tree) subproof(m, lo, hi int, complete bool) [][]byte {
	n := hi - lo
	if m == n {
		if complete {
			return nil
		}
		return [][]byte{t.mth(lo, hi)}
	}
	k := split(n)
	if m <= k {
		return append(t.subproof(m, lo, lo+k, complete), t.mth(lo+k, hi))
	}
	return append(t.subproof(m-k, lo+k, hi, false), t.mth(lo, lo+k))
}

// VerifyConsistency checks a consistency proof with the algorithm of
// RFC 9162 section 2.1.4.2.
func VerifyConsistency(first, second int, firstRoot, secondRoot []byte, proof [][]byte) bool {
	if first <= 0 || first > second {
		return false
	}
	if first == second {
		return len(proof) == 0 && bytes.Equal(firstRoot, secondRoot)
	}
	if len(proof) == 0 {
		return false
	}
	path := proof
	if first&(first-1) == 0 { // exact power of two
		path = append([][]byte{firstRoot}, proof...)
	}
	fn, sn := first-1, second-1
	for fn&1 == 1 {
		fn >>= 1
		sn >>= 1
	}
	fr, sr := path[0], path[0]
	for _, c := range path[1:] {
		if sn == 0 {
			return false
		}
		if fn&1 == 1 || fn == sn {
			fr = NodeHash(c, fr)
			sr = NodeHash(c, sr)
			for fn&1 == 0 && fn != 0 {
				fn >>= 1
				sn >>= 1
			}
		} else {
			sr = NodeHash(sr, c)
		}
		fn >>= 1
		sn >>= 1
	}
	return sn == 0 && bytes.Equal(fr, firstRoot) && bytes.Equal(sr, secondRoot)
}

// Diff compares two trees of the same size top-down, the way two replicas
// exchange hashes during anti-entropy: equal subtrees are skipped, unequal
// ones are split until single leaves remain. It returns the indexes of the
// divergent leaves and how many hash comparisons were needed.
func Diff(a, b *Tree) (leaves []int, compared int, err error) {
	if a.Size() != b.Size() {
		return nil, 0, ErrShape
	}
	var walk func(lo, hi int)
	walk = func(lo, hi int) {
		compared++
		if bytes.Equal(a.mth(lo, hi), b.mth(lo, hi)) {
			return
		}
		if hi-lo == 1 {
			leaves = append(leaves, lo)
			return
		}
		k := split(hi - lo)
		walk(lo, lo+k)
		walk(lo+k, hi)
	}
	if a.Size() > 0 {
		walk(0, a.Size())
	}
	return leaves, compared, nil
}

تست‌ها بردارهای آزمون منتشرشدهٔ Certificate Transparency (درخت خالی، یک برگ، هشت برگ)، همهٔ inclusion proofها و consistency proofها برای همهٔ اندازه‌ها تا ۷۰ و ۴۰، برگ جعلی و تاریخچهٔ بازنویسی‌شده، طول لگاریتمی اثبات و diff را وارسی می‌کنند:

go
package merkle

import (
	"bytes"
	"encoding/hex"
	"fmt"
	"testing"
)

// The eight inputs used by the Certificate Transparency reference test suite.
var ctInputs = [][]byte{
	{},
	{0x00},
	{0x10},
	{0x20, 0x21},
	{0x30, 0x31},
	{0x40, 0x41, 0x42, 0x43},
	{0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57},
	{0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f},
}

func hx(b []byte) string { return hex.EncodeToString(b) }

func TestKnownRoots(t *testing.T) {
	empty := New(nil)
	if got := hx(empty.Root()); got != "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" {
		t.Fatalf("empty root = %s", got)
	}
	tr := New(ctInputs)
	r1, _ := tr.RootAt(1)
	if got := hx(r1); got != "6e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d" {
		t.Fatalf("root(1) = %s", got)
	}
	if got := hx(tr.Root()); got != "5dc9da79a70659a9ad559cb701ded9a2ab9d823aad2f4960cfe370eff4604328" {
		t.Fatalf("root(8) = %s", got)
	}
}

func makeTree(n int) *Tree {
	data := make([][]byte, n)
	for i := range data {
		data[i] = []byte(fmt.Sprintf("leaf-%d", i))
	}
	return New(data)
}

func TestEveryInclusionProofVerifies(t *testing.T) {
	tr := makeTree(70)
	for size := 1; size <= 70; size++ {
		root, _ := tr.RootAt(size)
		for i := 0; i < size; i++ {
			proof, err := tr.InclusionProof(i, size)
			if err != nil {
				t.Fatal(err)
			}
			leaf := LeafHash([]byte(fmt.Sprintf("leaf-%d", i)))
			if !VerifyInclusion(leaf, i, size, proof, root) {
				t.Fatalf("size %d index %d: valid proof rejected", size, i)
			}
			if VerifyInclusion(LeafHash([]byte("forged")), i, size, proof, root) {
				t.Fatalf("size %d index %d: forged leaf accepted", size, i)
			}
			if size > 1 && VerifyInclusion(leaf, (i+1)%size, size, proof, root) {
				t.Fatalf("size %d index %d: proof accepted at the wrong index", size, i)
			}
		}
	}
}

func TestProofLengthIsLogarithmic(t *testing.T) {
	tr := makeTree(1 << 10)
	proof, _ := tr.InclusionProof(517, 1<<10)
	if len(proof) != 10 {
		t.Fatalf("audit path length = %d, want 10 for 1024 leaves", len(proof))
	}
}

func TestEveryConsistencyProofVerifies(t *testing.T) {
	tr := makeTree(40)
	for second := 1; second <= 40; second++ {
		r2, _ := tr.RootAt(second)
		for first := 1; first <= second; first++ {
			r1, _ := tr.RootAt(first)
			proof, err := tr.ConsistencyProof(first, second)
			if err != nil {
				t.Fatal(err)
			}
			if !VerifyConsistency(first, second, r1, r2, proof) {
				t.Fatalf("%d -> %d: valid consistency proof rejected", first, second)
			}
			if first < second && VerifyConsistency(first, second, LeafHash([]byte("x")), r2, proof) {
				t.Fatalf("%d -> %d: wrong old root accepted", first, second)
			}
		}
	}
}

func TestRewrittenHistoryFailsConsistency(t *testing.T) {
	honest := makeTree(8)
	oldRoot, _ := honest.RootAt(5)
	// A log that rewrote entry 2 after publishing the 5-entry root.
	data := make([][]byte, 8)
	for i := range data {
		data[i] = []byte(fmt.Sprintf("leaf-%d", i))
	}
	data[2] = []byte("rewritten")
	evil := New(data)
	proof, _ := evil.ConsistencyProof(5, 8)
	if VerifyConsistency(5, 8, oldRoot, evil.Root(), proof) {
		t.Fatal("rewritten history passed the consistency check")
	}
}

func TestDiffFindsOnlyDivergentLeaves(t *testing.T) {
	a, b := makeTree(1024), makeTree(1024)
	leaves, compared, err := Diff(a, b)
	if err != nil || len(leaves) != 0 || compared != 1 {
		t.Fatalf("identical: leaves=%v compared=%d err=%v", leaves, compared, err)
	}
	data := make([][]byte, 1024)
	for i := range data {
		data[i] = []byte(fmt.Sprintf("leaf-%d", i))
	}
	data[300] = []byte("changed")
	data[301] = []byte("changed too")
	c := New(data)
	leaves, compared, _ = Diff(a, c)
	if len(leaves) != 2 || leaves[0] != 300 || leaves[1] != 301 {
		t.Fatalf("divergent leaves = %v", leaves)
	}
	// 1 root + 2 per level for 9 levels, then 2 extra at the split of 300/301.
	if compared > 2*10+3 {
		t.Fatalf("compared %d hashes, want a logarithmic number", compared)
	}
	if _, _, err := Diff(a, makeTree(3)); err != ErrShape {
		t.Fatalf("want ErrShape, got %v", err)
	}
}

func TestAppendKeepsOldRoots(t *testing.T) {
	tr := makeTree(5)
	before, _ := tr.RootAt(5)
	tr.Append([]byte("leaf-5"))
	after, _ := tr.RootAt(5)
	if !bytes.Equal(before, after) {
		t.Fatal("appending changed the root of an older size")
	}
}

درخت anti-entropy. کلیدها به fanout^depth بازهٔ پیوستهٔ token می‌روند تا هر دو replica شکل یکسان بسازند؛ برگ‌ها ورودی‌های مرتب‌شده را، با tombstoneها، هش می‌کنند؛ Diff تعداد دور، هش‌های مقایسه‌شده و bucketهای واگرا را گزارش می‌دهد؛ InBuckets همان چیزی است که stream می‌شود:

go
// Package antientropy builds the fixed-shape hash trees that replicas compare
// during anti-entropy repair (Dynamo section 4.7, Cassandra repair, Riak AAE).
//
// Keys are placed into fanout^depth buckets by token (the first 8 bytes of
// SHA-256 of the key), so every bucket is a contiguous token range and two
// replicas of the same range build trees with identical shape. A leaf hashes
// the sorted entries of its bucket (tombstones included); an inner node
// hashes its children. Diff walks both trees level by level and only asks for
// the children of nodes that differ.
package antientropy

import (
	"bytes"
	"crypto/sha256"
	"encoding/binary"
	"errors"
	"sort"
	"strconv"
)

// Entry is one replicated cell. Deleted marks a tombstone.
type Entry struct {
	Key     string
	Value   string
	TS      int64 // write timestamp used for last-write-wins
	Deleted bool
}

// ErrShape is returned when two trees were built with different parameters.
var ErrShape = errors.New("antientropy: trees have different shapes")

// Token maps a key onto the 64-bit ring.
func Token(key string) uint64 {
	s := sha256.Sum256([]byte(key))
	return binary.BigEndian.Uint64(s[:8])
}

// Bucket maps a key to one of n contiguous token ranges.
func Bucket(key string, n int) int {
	hi := Token(key) >> 32
	return int(hi * uint64(n) >> 32)
}

// Tree is a complete fanout-ary hash tree. levels[0] holds the root,
// levels[depth] holds one hash per bucket.
type Tree struct {
	Fanout, Depth int
	levels        [][][]byte
}

// Buckets is the number of leaves (token ranges).
func (t *Tree) Buckets() int { return len(t.levels[t.Depth]) }

// Root is the root hash.
func (t *Tree) Root() []byte { return t.levels[0][0] }

// Build hashes a replica's entries. Cost: one pass over the data (the
// "validation compaction" that Cassandra runs before a repair session).
func Build(entries map[string]Entry, fanout, depth int) *Tree {
	n := 1
	for i := 0; i < depth; i++ {
		n *= fanout
	}
	buckets := make([][]Entry, n)
	for _, e := range entries {
		b := Bucket(e.Key, n)
		buckets[b] = append(buckets[b], e)
	}
	leaves := make([][]byte, n)
	for i, es := range buckets {
		sort.Slice(es, func(a, b int) bool { return es[a].Key < es[b].Key })
		h := sha256.New()
		for _, e := range es {
			h.Write([]byte(e.Key))
			h.Write([]byte{0})
			h.Write([]byte(e.Value))
			h.Write([]byte{0})
			h.Write([]byte(strconv.FormatInt(e.TS, 10)))
			if e.Deleted {
				h.Write([]byte{0, 'D'})
			}
			h.Write([]byte{'\n'})
		}
		leaves[i] = h.Sum(nil)
	}
	levels := make([][][]byte, depth+1)
	levels[depth] = leaves
	for d := depth - 1; d >= 0; d-- {
		below := levels[d+1]
		cur := make([][]byte, len(below)/fanout)
		for i := range cur {
			h := sha256.New()
			for _, c := range below[i*fanout : (i+1)*fanout] {
				h.Write(c)
			}
			cur[i] = h.Sum(nil)
		}
		levels[d] = cur
	}
	return &Tree{Fanout: fanout, Depth: depth, levels: levels}
}

// Stats describes one comparison between two replicas.
type Stats struct {
	Rounds         int   // request/response round trips (levels descended)
	HashesCompared int   // hashes sent over the network and compared
	Divergent      []int // buckets whose contents differ
}

// Diff compares two trees top-down. The cost is bounded by the number of
// differences: identical replicas exchange one root hash.
func Diff(a, b *Tree) (Stats, error) {
	if a.Fanout != b.Fanout || a.Depth != b.Depth {
		return Stats{}, ErrShape
	}
	st := Stats{Rounds: 1, HashesCompared: 1}
	if bytes.Equal(a.Root(), b.Root()) {
		return st, nil
	}
	frontier := []int{0}
	for d := 1; d <= a.Depth; d++ {
		st.Rounds++
		var next []int
		for _, parent := range frontier {
			for c := parent * a.Fanout; c < (parent+1)*a.Fanout; c++ {
				st.HashesCompared++
				if !bytes.Equal(a.levels[d][c], b.levels[d][c]) {
					next = append(next, c)
				}
			}
		}
		frontier = next
	}
	st.Divergent = frontier
	return st, nil
}

// InBuckets returns the entries of the given buckets: what a replica streams
// to its peer for the divergent ranges. Everything else stays put.
func InBuckets(entries map[string]Entry, buckets []int, n int) []Entry {
	want := make(map[int]bool, len(buckets))
	for _, b := range buckets {
		want[b] = true
	}
	var out []Entry
	for _, e := range entries {
		if want[Bucket(e.Key, n)] {
			out = append(out, e)
		}
	}
	sort.Slice(out, func(i, j int) bool { return out[i].Key < out[j].Key })
	return out
}
go
package antientropy

import (
	"fmt"
	"testing"
)

func dataset(n int) map[string]Entry {
	m := make(map[string]Entry, n)
	for i := 0; i < n; i++ {
		k := fmt.Sprintf("user:%05d", i)
		m[k] = Entry{Key: k, Value: "v1", TS: 1}
	}
	return m
}

func clone(m map[string]Entry) map[string]Entry {
	c := make(map[string]Entry, len(m))
	for k, v := range m {
		c[k] = v
	}
	return c
}

func TestIdenticalReplicasExchangeOneHash(t *testing.T) {
	a := dataset(10000)
	st, err := Diff(Build(a, 16, 3), Build(clone(a), 16, 3))
	if err != nil {
		t.Fatal(err)
	}
	if st.HashesCompared != 1 || st.Rounds != 1 || len(st.Divergent) != 0 {
		t.Fatalf("identical replicas: %+v", st)
	}
}

func TestOneChangedKeyCostsOnePathOfHashes(t *testing.T) {
	a := dataset(10000)
	b := clone(a)
	b["user:04242"] = Entry{Key: "user:04242", Value: "v2", TS: 2}
	st, _ := Diff(Build(a, 16, 3), Build(b, 16, 3))
	if len(st.Divergent) != 1 || st.Divergent[0] != Bucket("user:04242", 4096) {
		t.Fatalf("divergent = %v", st.Divergent)
	}
	if want := 1 + 16*3; st.HashesCompared != want || st.Rounds != 4 {
		t.Fatalf("compared %d hashes in %d rounds, want %d in 4", st.HashesCompared, st.Rounds, want)
	}
	streamed := InBuckets(b, st.Divergent, 4096)
	if len(streamed) > 10 {
		t.Fatalf("streamed %d entries for one changed key", len(streamed))
	}
}

func TestTombstoneIsADifference(t *testing.T) {
	a := dataset(100)
	b := clone(a)
	b["user:00007"] = Entry{Key: "user:00007", TS: 5, Deleted: true}
	st, _ := Diff(Build(a, 4, 2), Build(b, 4, 2))
	if len(st.Divergent) != 1 {
		t.Fatalf("a tombstone must change the bucket hash: %+v", st)
	}
}

func TestLowResolutionOverstreams(t *testing.T) {
	a := dataset(10000)
	b := clone(a)
	b["user:00001"] = Entry{Key: "user:00001", Value: "v2", TS: 2}
	coarse, _ := Diff(Build(a, 2, 2), Build(b, 2, 2)) // 4 buckets
	fine, _ := Diff(Build(a, 2, 12), Build(b, 2, 12)) // 4096 buckets
	nc := len(InBuckets(b, coarse.Divergent, 4))
	nf := len(InBuckets(b, fine.Divergent, 4096))
	if nc < 1000 || nf > 20 {
		t.Fatalf("coarse streamed %d, fine streamed %d", nc, nf)
	}
}

func TestShapeMismatch(t *testing.T) {
	if _, err := Diff(Build(nil, 2, 3), Build(nil, 4, 3)); err != ErrShape {
		t.Fatalf("want ErrShape, got %v", err)
	}
}

شبیه‌ساز replica. hinted handoff محدود به HintWindow، blocking read repair فقط روی replicaهای تماس‌گرفته، ترمیم مرکلی دوبه‌دو که فقط bucketهای واگرا را stream می‌کند، compaction که tombstoneها را پس از GCGrace پاک می‌کند، و دو حالت حذف:

go
// Package kvsim is a single-process simulation of a leaderless replicated
// key-value store (Dynamo / Cassandra style) with the three convergence
// mechanisms: hinted handoff on the write path, blocking read repair on the
// read path, and Merkle-tree anti-entropy repair in the background. Deletes
// are either hard (remove the local copy) or tombstones with a grace period,
// so the resurrection ("zombie") failure can be reproduced in a test.
package kvsim

import (
	"sort"

	"academy/merkle-trees-anti-entropy/antientropy"
)

// DeleteMode selects how Delete is implemented.
type DeleteMode int

const (
	// HardDelete removes the local copy. Absence carries no timestamp, so a
	// replica that missed the delete looks like the only one with data.
	HardDelete DeleteMode = iota
	// Tombstones writes a timestamped delete marker that replicates like data
	// and is purged by compaction after GCGrace seconds.
	Tombstones
)

// Config mirrors the knobs of a real store.
type Config struct {
	Replicas   []string
	Mode       DeleteMode
	GCGrace    int64 // like Cassandra gc_grace_seconds
	HintWindow int64 // like Cassandra max_hint_window (seconds)
	Fanout     int   // Merkle tree branching factor
	Depth      int   // Merkle tree depth; buckets = Fanout^Depth
}

// Stats counts what each mechanism did.
type Stats struct {
	HintsStored, HintsDropped, HintsReplayed int
	ReadRepairs                              int
	RepairStreamed, RepairHashes             int
	TombstonesPurged                         int
}

type op struct {
	e      antientropy.Entry
	remove bool
}

type replica struct {
	up        bool
	downSince int64
	data      map[string]antientropy.Entry
}

// Cluster holds every replica and a logical clock in seconds.
type Cluster struct {
	cfg   Config
	now   int64
	seq   int64
	names []string
	reps  map[string]*replica
	hints map[string][]op
	Stats Stats
}

// New starts a cluster with every replica up at time 0.
func New(cfg Config) *Cluster {
	c := &Cluster{cfg: cfg, reps: map[string]*replica{}, hints: map[string][]op{}}
	for _, n := range cfg.Replicas {
		c.names = append(c.names, n)
		c.reps[n] = &replica{up: true, data: map[string]antientropy.Entry{}}
	}
	return c
}

// Now is the logical time in seconds.
func (c *Cluster) Now() int64 { return c.now }

// ts returns a unique, increasing write timestamp (milliseconds).
func (c *Cluster) ts() int64 {
	c.seq++
	return c.now*1000 + c.seq%1000
}

// Advance moves the clock and runs compaction on every live replica:
// tombstones older than GCGrace are purged.
func (c *Cluster) Advance(seconds int64) {
	c.now += seconds
	for _, n := range c.names {
		r := c.reps[n]
		if !r.up {
			continue
		}
		for k, e := range r.data {
			if e.Deleted && c.now-e.TS/1000 > c.cfg.GCGrace {
				delete(r.data, k)
				c.Stats.TombstonesPurged++
			}
		}
	}
}

// Down marks a replica unreachable.
func (c *Cluster) Down(name string) {
	r := c.reps[name]
	r.up, r.downSince = false, c.now
}

// Up brings a replica back and replays the hints stored for it.
func (c *Cluster) Up(name string) {
	r := c.reps[name]
	r.up = true
	for _, h := range c.hints[name] {
		c.apply(r, h)
		c.Stats.HintsReplayed++
	}
	delete(c.hints, name)
}

// Put writes key = value to every replica (down replicas get a hint).
func (c *Cluster) Put(key, value string) {
	c.write(op{e: antientropy.Entry{Key: key, Value: value, TS: c.ts()}})
}

// Delete removes key according to the configured DeleteMode.
func (c *Cluster) Delete(key string) {
	if c.cfg.Mode == Tombstones {
		c.write(op{e: antientropy.Entry{Key: key, TS: c.ts(), Deleted: true}})
		return
	}
	c.write(op{e: antientropy.Entry{Key: key}, remove: true})
}

func (c *Cluster) write(o op) {
	for _, n := range c.names {
		r := c.reps[n]
		switch {
		case r.up:
			c.apply(r, o)
		case c.now-r.downSince <= c.cfg.HintWindow:
			c.hints[n] = append(c.hints[n], o)
			c.Stats.HintsStored++
		default:
			c.Stats.HintsDropped++ // outside the hint window: only repair can fix it
		}
	}
}

func (c *Cluster) apply(r *replica, o op) {
	if o.remove {
		delete(r.data, o.e.Key)
		return
	}
	if cur, ok := r.data[o.e.Key]; !ok || cur.TS < o.e.TS {
		r.data[o.e.Key] = o.e
	}
}

// Read asks the named replicas (the consistency level is len(from)), returns
// the newest version, and performs a blocking read repair on every contacted
// replica whose digest differs before returning.
func (c *Cluster) Read(key string, from ...string) (string, bool) {
	var win antientropy.Entry
	have := false
	got := make(map[string]antientropy.Entry, len(from))
	for _, n := range from {
		r := c.reps[n]
		if !r.up {
			continue
		}
		e, ok := r.data[key]
		if ok {
			got[n] = e
			if !have || e.TS > win.TS {
				win, have = e, true
			}
		}
	}
	if !have {
		return "", false
	}
	repaired := false
	for _, n := range from {
		r := c.reps[n]
		if !r.up {
			continue
		}
		if e, ok := got[n]; !ok || e != win { // digest mismatch
			c.apply(r, op{e: win})
			repaired = true
		}
	}
	if repaired {
		c.Stats.ReadRepairs++
	}
	if win.Deleted {
		return "", false
	}
	return win.Value, true
}

// Repair runs Merkle-tree anti-entropy between every pair of live replicas
// and streams only the entries of divergent buckets, in both directions.
func (c *Cluster) Repair() {
	live := make([]string, 0, len(c.names))
	for _, n := range c.names {
		if c.reps[n].up {
			live = append(live, n)
		}
	}
	sort.Strings(live)
	buckets := 1
	for i := 0; i < c.cfg.Depth; i++ {
		buckets *= c.cfg.Fanout
	}
	for i := 0; i < len(live); i++ {
		for j := i + 1; j < len(live); j++ {
			a, b := c.reps[live[i]], c.reps[live[j]]
			st, _ := antientropy.Diff(
				antientropy.Build(a.data, c.cfg.Fanout, c.cfg.Depth),
				antientropy.Build(b.data, c.cfg.Fanout, c.cfg.Depth))
			c.Stats.RepairHashes += st.HashesCompared
			if len(st.Divergent) == 0 {
				continue
			}
			fromA := antientropy.InBuckets(a.data, st.Divergent, buckets)
			fromB := antientropy.InBuckets(b.data, st.Divergent, buckets)
			for _, e := range fromA {
				c.apply(b, op{e: e})
			}
			for _, e := range fromB {
				c.apply(a, op{e: e})
			}
			c.Stats.RepairStreamed += len(fromA) + len(fromB)
		}
	}
}

// Peek returns a replica's local cell without any repair, for tests.
func (c *Cluster) Peek(name, key string) (antientropy.Entry, bool) {
	e, ok := c.reps[name].data[key]
	return e, ok
}

تست‌ها ادعاهای فصل به شکل کدند: حذف سخت با repair و با read repair زنده می‌شود، tombstone از repair جان سالم به در می‌برد، tombstoneی که پیش از repair پاک شده زامبی می‌سازد، hint درون پنجره کار می‌کند، read repair فقط replicaهای تماس‌گرفته را درست می‌کند، و هزینهٔ repair دنبال تفاوت می‌رود:

go
package kvsim

import (
	"fmt"
	"testing"
)

const (
	hour = int64(3600)
	day  = 24 * hour
)

func cluster(mode DeleteMode, grace int64) *Cluster {
	return New(Config{
		Replicas: []string{"a", "b", "c"}, Mode: mode,
		GCGrace: grace, HintWindow: 3 * hour, Fanout: 16, Depth: 2,
	})
}

// c goes down, stays down past the hint window, misses the delete, and
// comes back `after` seconds later.
func missDelete(c *Cluster, after int64) {
	c.Put("cart:42", "3 items")
	c.Down("c")
	c.Advance(4 * hour) // beyond max_hint_window: no hint for c
	c.Delete("cart:42")
	c.Advance(after)
	c.Up("c")
}

func TestHardDeleteIsResurrectedByRepair(t *testing.T) {
	c := cluster(HardDelete, 10*day)
	missDelete(c, 1*hour)
	c.Repair()
	if v, ok := c.Read("cart:42", "a", "b", "c"); !ok || v != "3 items" {
		t.Fatalf("expected the deleted cart to come back, got %q %v", v, ok)
	}
}

func TestHardDeleteIsResurrectedByReadRepairToo(t *testing.T) {
	c := cluster(HardDelete, 10*day)
	missDelete(c, 1*hour)
	if _, ok := c.Read("cart:42", "a", "c"); !ok {
		t.Fatal("a read that touches c sees the old row")
	}
	if _, ok := c.Peek("a", "cart:42"); !ok {
		t.Fatal("read repair copied the deleted row back to a")
	}
}

func TestTombstoneSurvivesRepair(t *testing.T) {
	c := cluster(Tombstones, 10*day)
	missDelete(c, 1*hour)
	if c.Stats.HintsDropped == 0 {
		t.Fatal("the delete should have fallen outside the hint window")
	}
	c.Repair()
	if _, ok := c.Read("cart:42", "a", "b", "c"); ok {
		t.Fatal("tombstone did not win")
	}
	if e, _ := c.Peek("c", "cart:42"); !e.Deleted {
		t.Fatal("repair should have streamed the tombstone to c")
	}
}

func TestTombstonePurgedBeforeRepairMakesAZombie(t *testing.T) {
	c := cluster(Tombstones, 1*day) // gc_grace shorter than the outage
	missDelete(c, 2*day)
	if c.Stats.TombstonesPurged != 2 {
		t.Fatalf("purged %d tombstones, want 2 (on a and b)", c.Stats.TombstonesPurged)
	}
	c.Repair()
	if v, ok := c.Read("cart:42", "a", "b"); !ok || v != "3 items" {
		t.Fatalf("expected a zombie, got %q %v", v, ok)
	}
}

func TestHintedHandoffInsideTheWindow(t *testing.T) {
	c := cluster(Tombstones, 10*day)
	c.Put("k", "v1")
	c.Down("c")
	c.Advance(1 * hour)
	c.Put("k", "v2")
	c.Up("c")
	if e, _ := c.Peek("c", "k"); e.Value != "v2" || c.Stats.HintsReplayed != 1 {
		t.Fatalf("hint not replayed: %+v %+v", e, c.Stats)
	}
}

func TestBlockingReadRepairFixesOnlyContactedReplicas(t *testing.T) {
	c := cluster(Tombstones, 10*day)
	c.Put("k", "v1")
	c.Down("c")
	c.Down("b")
	c.Advance(4 * hour) // past the hint window: no hints for b and c
	c.Put("k", "v2")
	c.Up("b")
	c.Up("c")
	if v, _ := c.Read("k", "a", "b"); v != "v2" {
		t.Fatalf("read returned %q", v)
	}
	if e, _ := c.Peek("b", "k"); e.Value != "v2" {
		t.Fatal("b was contacted and should be repaired")
	}
	if e, _ := c.Peek("c", "k"); e.Value != "v1" {
		t.Fatal("c was not contacted and must still be stale")
	}
	if c.Stats.ReadRepairs != 1 {
		t.Fatalf("read repairs = %d", c.Stats.ReadRepairs)
	}
}

func TestRepairCostFollowsTheDifference(t *testing.T) {
	c := cluster(Tombstones, 10*day)
	for i := 0; i < 5000; i++ {
		c.Put(fmt.Sprintf("user:%d", i), "v1")
	}
	c.Repair()
	if c.Stats.RepairStreamed != 0 || c.Stats.RepairHashes != 3 {
		t.Fatalf("in-sync replicas: %+v", c.Stats)
	}
	c.Down("c")
	c.Advance(4 * hour)
	c.Put("user:77", "v2")
	c.Up("c")
	c.Repair()
	if c.Stats.RepairStreamed > 2*60 {
		t.Fatalf("streamed %d entries for one missed write", c.Stats.RepairStreamed)
	}
}

راه‌انداز آزمایشگاه:

go
// Command aesim prints the lab output of the Merkle Trees, Read Repair,
// Anti-Entropy & Tombstones chapter: proofs, tree diff cost, branching
// factor trade-off, and the three delete scenarios.
package main

import (
	"encoding/hex"
	"fmt"

	"academy/merkle-trees-anti-entropy/antientropy"
	"academy/merkle-trees-anti-entropy/kvsim"
	"academy/merkle-trees-anti-entropy/merkle"
)

const hour = int64(3600)

func main() {
	proofs()
	fanout()
	deletes()
}

func proofs() {
	fmt.Println("== 1. RFC 6962 tree: root, inclusion proof, consistency proof")
	data := make([][]byte, 1_000_000)
	for i := range data {
		data[i] = []byte(fmt.Sprintf("cert-%d", i))
	}
	t := merkle.New(data)
	root := t.Root()
	p, _ := t.InclusionProof(123456, t.Size())
	ok := merkle.VerifyInclusion(merkle.LeafHash(data[123456]), 123456, t.Size(), p, root)
	fmt.Printf("leaves=%d root=%s...\n", t.Size(), hex.EncodeToString(root)[:16])
	fmt.Printf("inclusion proof for leaf 123456: %d hashes (%d bytes), valid=%v\n", len(p), 32*len(p), ok)
	old, _ := t.RootAt(600_000)
	cp, _ := t.ConsistencyProof(600_000, t.Size())
	fmt.Printf("consistency proof 600000 -> 1000000: %d hashes, valid=%v\n",
		len(cp), merkle.VerifyConsistency(600_000, t.Size(), old, root, cp))
}

func fanout() {
	fmt.Println("== 2. one divergent key among 100000: cost by branching factor")
	a := map[string]antientropy.Entry{}
	for i := 0; i < 100_000; i++ {
		k := fmt.Sprintf("user:%06d", i)
		a[k] = antientropy.Entry{Key: k, Value: "v1", TS: 1}
	}
	b := make(map[string]antientropy.Entry, len(a))
	for k, v := range a {
		b[k] = v
	}
	b["user:031337"] = antientropy.Entry{Key: "user:031337", Value: "v2", TS: 2}
	fmt.Printf("%-7s %-6s %-8s %-7s %-7s %s\n", "fanout", "depth", "buckets", "rounds", "hashes", "streamed")
	for _, s := range []struct{ f, d int }{{2, 4}, {2, 16}, {4, 8}, {16, 4}, {256, 2}, {65536, 1}} {
		st, _ := antientropy.Diff(antientropy.Build(a, s.f, s.d), antientropy.Build(b, s.f, s.d))
		n := 1
		for i := 0; i < s.d; i++ {
			n *= s.f
		}
		fmt.Printf("%-7d %-6d %-8d %-7d %-7d %d\n", s.f, s.d, n, st.Rounds, st.HashesCompared,
			len(antientropy.InBuckets(b, st.Divergent, n)))
	}
}

func deletes() {
	fmt.Println("== 3. replica c misses a delete (down 4h, hint window 3h)")
	for _, sc := range []struct {
		name  string
		mode  kvsim.DeleteMode
		grace int64
		after int64
	}{
		{"hard delete", kvsim.HardDelete, 240 * hour, hour},
		{"tombstone, gc_grace 10d, back after 5h", kvsim.Tombstones, 240 * hour, hour},
		{"tombstone, gc_grace 1d, back after 2d", kvsim.Tombstones, 24 * hour, 48 * hour},
	} {
		c := kvsim.New(kvsim.Config{Replicas: []string{"a", "b", "c"}, Mode: sc.mode,
			GCGrace: sc.grace, HintWindow: 3 * hour, Fanout: 16, Depth: 2})
		c.Put("cart:42", "3 items")
		c.Down("c")
		c.Advance(4 * hour)
		c.Delete("cart:42")
		c.Advance(sc.after)
		c.Up("c")
		c.Repair()
		v, found := c.Read("cart:42", "a", "b", "c")
		fmt.Printf("%-40s hints_dropped=%d purged=%d streamed=%d -> read found=%v %q\n",
			sc.name, c.Stats.HintsDropped, c.Stats.TombstonesPurged, c.Stats.RepairStreamed, found, v)
	}
}

نگاه Go ​

بسته یا کلاینت Goکاربرد در اینجانکته
crypto/sha256هش برگ و گرهsha256.Sum256(nil) ریشهٔ درخت خالی در RFC 6962 است
encoding/binarytoken از ۸ بایت اول یک هشbinary.BigEndian.Uint64
golang.org/x/mod/sumdb/tlogدرخت تولیدی به سبک RFC 6962 که پایگاه checksum در Go به کار می‌بردtileها، ProveRecord، CheckRecord، ProveTree، CheckTree
github.com/transparency-dev/merklehasherهای RFC 6962 و وارسی اثباتمنبع بردارهای آزمون بالا
github.com/gocql/gocqlخواندن Cassandra با gocql.Quorum / gocql.LocalQuorumread repair فقط بالاتر از ONE رخ می‌دهد
github.com/twmb/franz-go/pkg/kgotombstone در Kafka: یک *kgo.Record با Key و Value: nilفقط روی topicهای cleanup.policy=compact معنا دارد
database/sql / github.com/jackc/pgx/v5soft delete و prune دسته‌ای (SQL در حل مسئله‌ها)در دسته‌های کوچک prune کنید تا قفل‌ها کوتاه بمانند
testingهر ادعای این صفحه یک تست استgo test ./... در کمتر از یک ثانیه اجرا می‌شود

Laravel ​

Before ​

API همگام‌سازی‌ای که hard delete می‌کند و می‌گذارد کلاینت‌ها updated_at > since را poll کنند: سندهای حذف‌شده هرگز در پاسخ ظاهر نمی‌شوند، پس کلاینت‌های آفلاین نگهشان می‌دارند و دوباره آپلودشان می‌کنند.

php
<?php

namespace App\Http\Controllers\Before;

use App\Http\Controllers\Controller;
use App\Models\Document;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * The first version of an offline-capable sync API.
 *
 * - destroy() removes the row, so nothing records that the document existed.
 * - changes() returns rows updated since the client's last sync. A deleted row
 *   is simply absent, which looks the same as "unchanged" to the client, so an
 *   offline phone keeps the document and uploads it again on its next push.
 */
class DocumentSyncBefore extends Controller
{
    public function destroy(string $id): JsonResponse
    {
        DB::table('documents')->where('id', $id)->delete();

        return response()->json(status: 204);
    }

    public function changes(Request $request): JsonResponse
    {
        $since = $request->date('since') ?? now()->subYears(10);

        $rows = Document::query()
            ->where('updated_at', '>', $since)
            ->orderBy('updated_at')
            ->limit(1000)
            ->get(['id', 'version', 'payload', 'updated_at']);

        return response()->json(['changes' => $rows, 'server_time' => now()->toIso8601String()]);
    }
}

After ​

مدل: SoftDeletes فراخوانی delete() را به tombstone (deleted_at) تبدیل می‌کند، Prunable garbage collector با دورهٔ مهلت قابل‌تنظیم است، و هر save نسخه (version) را بالا می‌برد و ردیف را به bucket مرکلی‌اش سنجاق می‌کند:

php
<?php

namespace App\Models;

use App\Support\MerkleIndex;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Prunable;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * A document that offline clients replicate.
 *
 * SoftDeletes turns delete() into a tombstone (deleted_at is set, the row
 * stays), so the sync endpoint can tell clients "this was deleted". Prunable
 * is the garbage collector: tombstones older than the grace period are
 * removed for good by the scheduled model:prune command.
 */
class Document extends Model
{
    use HasUuids;
    use Prunable;
    use SoftDeletes;

    protected $fillable = ['title', 'payload'];

    protected function casts(): array
    {
        return [
            'payload' => 'array',
            'version' => 'integer',
            'sync_bucket' => 'integer',
        ];
    }

    protected static function booted(): void
    {
        // Every save (create, update, restore) bumps the version and pins the
        // row to its Merkle bucket. delete() on a soft-deleting model does not
        // call save(); the deleted flag itself changes the bucket hash.
        static::saving(function (Document $document): void {
            // HasUuids assigns the key in "creating", which runs after
            // "saving", so assign it here when the row is new.
            if (! $document->getKey()) {
                $document->setAttribute($document->getKeyName(), $document->newUniqueId());
            }
            $document->version = ($document->version ?? 0) + 1;
            $document->sync_bucket = MerkleIndex::bucketFor((string) $document->getKey());
        });
    }

    /**
     * Tombstones past the grace period. Prunable force-deletes soft-deleted
     * models that match this query.
     */
    public function prunable(): Builder
    {
        return static::onlyTrashed()
            ->where('deleted_at', '<=', now()->subDays((int) config('sync.tombstone_grace_days')));
    }

    /**
     * Runs before each row is removed for good: clean up stored files here.
     */
    protected function pruning(): void
    {
        // Storage::delete($this->attachment_path);
    }
}

شاخص مرکلی: ۲۵۶ bucket با کلید بایت اول SHA-256 شناسه، برگ‌ها خط‌های id:version:deleted را با پیشوند 0x00 هش می‌کنند و گره‌ها با 0x01:

php
<?php

namespace App\Support;

use InvalidArgumentException;

/**
 * A two-level Merkle tree over 256 buckets, with the RFC 6962 hashing rules:
 * leaf = SHA-256(0x00 || bucket contents), node = SHA-256(0x01 || left || right).
 *
 * The leaf contents are the sorted lines "id:version:deleted" of the bucket,
 * tombstones included, so a delete changes the hash exactly like an update.
 */
final class MerkleIndex
{
    public const BUCKETS = 256;

    /** The bucket of a row: the first byte of SHA-256 of its id. */
    public static function bucketFor(string $id): int
    {
        return hexdec(substr(hash('sha256', $id), 0, 2));
    }

    /**
     * @param  iterable<array{id: string, version: int, deleted: bool}>  $rows
     */
    public static function leafHash(iterable $rows): string
    {
        $lines = [];
        foreach ($rows as $row) {
            $lines[] = $row['id'].':'.$row['version'].':'.($row['deleted'] ? 1 : 0);
        }
        sort($lines, SORT_STRING);

        return hash('sha256', "\x00".implode("\n", $lines));
    }

    /**
     * @param  list<string>  $leafHashes  hex, one per bucket, in bucket order
     */
    public static function root(array $leafHashes): string
    {
        if (count($leafHashes) !== self::BUCKETS) {
            throw new InvalidArgumentException('expected '.self::BUCKETS.' bucket hashes');
        }

        $level = array_map(hex2bin(...), $leafHashes);
        while (count($level) > 1) {
            $next = [];
            for ($i = 0; $i < count($level); $i += 2) {
                $next[] = hash('sha256', "\x01".$level[$i].$level[$i + 1], true);
            }
            $level = $next;
        }

        return bin2hex($level[0]);
    }

    /**
     * Bucket indexes whose hashes differ between server and client.
     *
     * @param  list<string>  $server
     * @param  list<string>  $client
     * @return list<int>
     */
    public static function divergent(array $server, array $client): array
    {
        $out = [];
        foreach ($server as $i => $hash) {
            if (! hash_equals($hash, $client[$i] ?? '')) {
                $out[] = $i;
            }
        }

        return $out;
    }
}

endpointهای همگام‌سازی: مقایسهٔ ریشه، بعد یک دور هش bucketها؛ ردیف‌های bucketهای واگرا با withTrashed() برگردانده می‌شوند تا حذف‌ها هم برسند؛ کلاینت‌های قدیمی‌تر از دورهٔ مهلت 409 می‌گیرند و باید resync کنند:

php
<?php

namespace App\Http\Controllers;

use App\Models\Document;
use App\Support\MerkleIndex;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

/**
 * Merkle-based sync for offline clients.
 *
 * 1. GET  /sync/root  -> the root hash. Equal to the client's root: done.
 * 2. POST /sync/diff  -> the client sends its 256 bucket hashes; the server
 *    answers with every row (tombstones included) of the divergent buckets.
 *
 * A client whose last sync is older than the tombstone grace period may hold
 * rows whose tombstones were already pruned, so it must resync from scratch:
 * the same rule as repairing every Cassandra node within gc_grace_seconds.
 */
class SyncController extends Controller
{
    public function root(): JsonResponse
    {
        return response()->json([
            'root' => MerkleIndex::root($this->bucketHashes()),
            'buckets' => MerkleIndex::BUCKETS,
            'tombstone_grace_days' => (int) config('sync.tombstone_grace_days'),
            'server_time' => now()->toIso8601String(),
        ]);
    }

    public function diff(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'last_synced_at' => ['required', 'date'],
            'buckets' => ['required', 'array', 'size:'.MerkleIndex::BUCKETS],
            'buckets.*' => ['required', 'string', 'regex:/^[0-9a-f]{64}$/'],
        ]);

        $grace = (int) config('sync.tombstone_grace_days');
        if ($request->date('last_synced_at')->lt(now()->subDays($grace))) {
            return response()->json(['resync_required' => true], 409);
        }

        $divergent = MerkleIndex::divergent($this->bucketHashes(), array_values($validated['buckets']));

        $rows = Document::withTrashed()
            ->whereIn('sync_bucket', $divergent)
            ->orderBy('id')
            ->get(['id', 'version', 'title', 'payload', 'deleted_at'])
            ->map(fn (Document $d): array => [
                'id' => $d->id,
                'version' => $d->version,
                'deleted' => $d->trashed(),
                'title' => $d->trashed() ? null : $d->title,
                'payload' => $d->trashed() ? null : $d->payload,
            ]);

        return response()->json([
            'divergent_buckets' => $divergent,
            'rows' => $rows,
            'server_time' => now()->toIso8601String(),
        ]);
    }

    /**
     * One hash per bucket, tombstones included. For large tables keep these
     * in a sync_buckets table updated on write instead of scanning.
     *
     * @return list<string>
     */
    private function bucketHashes(): array
    {
        $byBucket = array_fill(0, MerkleIndex::BUCKETS, []);

        Document::withTrashed()
            ->toBase()
            ->select(['id', 'version', 'deleted_at', 'sync_bucket'])
            ->lazyById(2000, 'id')
            ->each(function (object $row) use (&$byBucket): void {
                $byBucket[(int) $row->sync_bucket][] = [
                    'id' => (string) $row->id,
                    'version' => (int) $row->version,
                    'deleted' => $row->deleted_at !== null,
                ];
            });

        return array_map(MerkleIndex::leafHash(...), $byBucket);
    }
}
php
<?php

use App\Http\Controllers\SyncController;
use Illuminate\Support\Facades\Route;

Route::middleware('auth:sanctum')->group(function () {
    Route::get('/sync/root', [SyncController::class, 'root']);
    Route::post('/sync/diff', [SyncController::class, 'diff']);
});

پیکربندی، schema و زمان‌بندی prune (onOneServer() و withoutOverlapping() تا دو سرور هرگز هم‌زمان prune نکنند):

php
<?php

return [
    // How long a soft-deleted row (tombstone) is kept before model:prune
    // removes it. Clients offline longer than this must resync from scratch.
    'tombstone_grace_days' => (int) env('SYNC_TOMBSTONE_GRACE_DAYS', 30),
];
php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('documents', function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->string('title');
            $table->json('payload')->nullable();
            $table->unsignedInteger('version')->default(0);
            $table->unsignedSmallInteger('sync_bucket');
            $table->timestamps();
            $table->softDeletes(); // deleted_at: the tombstone
            $table->index(['sync_bucket', 'id']);
            $table->index('deleted_at'); // the pruning query scans by age
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('documents');
    }
};
php
<?php

use App\Models\Document;
use Illuminate\Support\Facades\Schedule;

// Tombstone garbage collection. Run on one server only, never overlapping,
// and keep the grace period longer than the longest supported offline time.
Schedule::command('model:prune', ['--model' => [Document::class]])
    ->dailyAt('03:30')
    ->onOneServer()
    ->withoutOverlapping();

تست‌ها برای قواعد هش (tombstone برگ و ریشه را عوض می‌کند، ترتیب ردیف‌ها مهم نیست):

php
<?php

namespace Tests\Unit;

use App\Support\MerkleIndex;
use PHPUnit\Framework\TestCase;

class MerkleIndexTest extends TestCase
{
    public function test_empty_buckets_have_a_stable_root(): void
    {
        $leaves = array_fill(0, MerkleIndex::BUCKETS, MerkleIndex::leafHash([]));

        $this->assertSame(MerkleIndex::root($leaves), MerkleIndex::root($leaves));
        $this->assertSame(64, strlen(MerkleIndex::root($leaves)));
    }

    public function test_a_tombstone_changes_the_leaf_and_the_root(): void
    {
        $live = [['id' => 'a1', 'version' => 3, 'deleted' => false]];
        $dead = [['id' => 'a1', 'version' => 3, 'deleted' => true]];
        $this->assertNotSame(MerkleIndex::leafHash($live), MerkleIndex::leafHash($dead));

        $server = array_fill(0, MerkleIndex::BUCKETS, MerkleIndex::leafHash([]));
        $client = $server;
        $server[17] = MerkleIndex::leafHash($dead);
        $client[17] = MerkleIndex::leafHash($live);

        $this->assertNotSame(MerkleIndex::root($server), MerkleIndex::root($client));
        $this->assertSame([17], MerkleIndex::divergent($server, $client));
    }

    public function test_row_order_does_not_matter(): void
    {
        $a = ['id' => 'a', 'version' => 1, 'deleted' => false];
        $b = ['id' => 'b', 'version' => 2, 'deleted' => false];
        $this->assertSame(MerkleIndex::leafHash([$a, $b]), MerkleIndex::leafHash([$b, $a]));
    }

    public function test_buckets_are_in_range(): void
    {
        foreach (['0', 'x', '0195d7a2-6c1e-7a8b-9f00-000000000000'] as $id) {
            $bucket = MerkleIndex::bucketFor($id);
            $this->assertGreaterThanOrEqual(0, $bucket);
            $this->assertLessThan(MerkleIndex::BUCKETS, $bucket);
        }
    }
}

نگاه Laravel ​

قابلیت Laravelنقش در این فصلنکته (مستندات Laravel 13)
trait SoftDeletes، $table->softDeletes()ستون tombstone یعنی deleted_at"a deleted_at attribute is set on the model indicating the date and time at which the model was "deleted""
withTrashed() / onlyTrashed()tombstoneها را در هش‌ها و پاسخ‌های همگام‌سازی بیاوربدون آن، حذف‌ها برای API همگام‌سازی نامرئی‌اند
trashed()تشخیص tombstone از ردیف زندهبرای null کردن payload ردیف‌های حذف‌شده در پاسخ
restore()undo درون دورهٔ مهلتrestore() گروهی هیچ model event نمی‌فرستد
forceDelete()حذف برای همیشههمان چیزی که Prunable برای مدل‌های soft-deleted صدا می‌زند
Prunable + prunable() + pruning()garbage collection با پاک‌سازی مخصوص هر مدل"Soft deleting models will be permanently deleted (forceDelete) if they match the prunable query"
MassPrunableیک کوئری DELETE، بی eventسریع‌تر؛ pruning() صدا زده نمی‌شود
Schedule::command('model:prune')GC روزانه--model، --except، --pretend
onOneServer()، withoutOverlapping()هر بار یک prunerبه cache driver مشترک برای قفل نیاز دارد
lazyById()هش bucketها بدون بارکردن کل جدولقطعه‌قطعه بر اساس کلید اصلی
Model eventها (trashed، forceDeleted، restored)فرستادن invalidation به کش یا جست‌وجوtrashed هنگام soft delete رخ می‌دهد

حل مسئله‌های کلاسیک ​

دادهٔ حذف‌شده برگشت (ردیف‌های زامبی) ​

نشانه: ردیف‌هایی که روزها پیش حذف شده‌اند دوباره برگردانده می‌شوند، معمولاً بعد از این‌که یک node دوباره به خوشه پیوست یا از snapshot بازیابی شد. علت: یک replica حذف را از دست داده و tombstone (قدیمی‌تر از gc_grace_seconds) پیش از repair آن replica پاک شده، یا حذف در سیستمی که replicaها را ادغام می‌کند hard delete بوده.

راه‌حلچطورمزیتهزینه / محدودیت
آهنگ repair کمتر از دورهٔ مهلتfull یا incremental repair همهٔ nodeها، تمام‌شده درون gc_grace_seconds منهای حاشیهخودِ تضمینI/O دیسک و شبکه در یک برنامهٔ زمانی
بازسازی، نه پیوستن دوبارهnodeی که بیش از gc_grace_seconds خاموش بوده پاک و دوباره bootstrap می‌شودهیچ دادهٔ کهنه‌ای وارد نمی‌شودstream کردن یک node کامل
check_data_resurrectionوارسی راه‌اندازی در cassandra.yamlاشتباه را دم در می‌گیردباید روشن شود؛ فایل heartbeat برای هر node
only_purge_repaired_tombstonescompaction فقط از دادهٔ repaired tombstone پاک می‌کندپاک‌سازی نمی‌تواند از repair جلو بزنداگر repair بایستد tombstoneها انباشته می‌شوند
حذف دوبارهحذف را با timestamp تازه‌تر دوباره صادر کنیدمجموعهٔ معلومی از کلیدها را درست می‌کندباید بدانید کدام کلیدها برگشته‌اند
sql
-- Cassandra (CQL): keep the grace period above the repair cycle, purge only repaired data
ALTER TABLE shop.carts
  WITH gc_grace_seconds = 864000
  AND compaction = {'class': 'SizeTieredCompactionStrategy', 'only_purge_repaired_tombstones': 'true'};

-- re-delete known zombies with a timestamp newer than any old copy (microseconds)
DELETE FROM shop.carts USING TIMESTAMP 1795651200000000 WHERE cart_id = 42;

repair تمام نمی‌شود یا خیلی زیاد stream می‌کند ​

نشانه: repair یک جدول برای چند ردیف تغییرکرده گیگابایت‌ها stream می‌کند یا هرگز درون پنجره تمام نمی‌شود. علت: وضوح کم درخت (کلید زیاد در هر برگ)، repair کل node، اجراهای هم‌پوشان repair.

راه‌حلچطورمزیتهزینه / محدودیت
Subrange repairnodetool repair -st <start> -et <end>، یا segmentهای Reaper، یا splitterهای Auto Repairوضوح بیشتر برای هر درخت، واحدهای کوچک قابل تکرارجلسه‌های زیاد برای هماهنگی
حافظهٔ بیشتر برای درختrepair_session_space را بالا ببرید؛ concurrent_merkle_tree_requests را تنظیم کنیدبایت over-streamed کمترفشار روی heap
incremental بین اجراهای fullnodetool repair (پیش‌فرض) روزانه، --full هفتگیدادهٔ از قبل repaired رد می‌شودمجموعهٔ repaired دوباره بررسی نمی‌شود
اول previewnodetool repair --previewstream موردانتظار را بی انجامش نشان می‌دهدباز هم درخت می‌سازد
یک زمان‌بندReaper یا Auto Repair، نه هر دو به‌اضافهٔ cronجلسهٔ هم‌پوشان نداردابزاری برای اداره

کوئری‌ها با TombstoneOverwhelmingException شکست می‌خورند ​

نشانه: Scanned over 100001 tombstones during query ...; query aborted، که هفته‌ها پیش از آن هشدار tombstone آمده. علت: الگوی دسترسی پرحذف درون یک partition (جدول‌های صف، نگهداری «قدیمی‌ترین را حذف کن»، بازنویسی مجموعه‌ها).

راه‌حلچطورمزیتهزینه / محدودیت
partitionهای سطل‌بندی‌شده با زمانpartition key شامل روز یا ساعت؛ کل سطل‌ها را حذف کنیدیک partition tombstone برای هر سطلکوئری‌ها چند سطل را می‌پیمایند
TTL + Time Window CompactionUSING TTL و پنجره‌های TWCSکل SSTableها منقضی می‌شونددادهٔ TTLدار و بی‌TTL را مخلوط نکنید
حذف بازه‌ایDELETE ... WHERE pk = ? AND ts < ?یک range tombstoneخواندن‌ها هنوز باید از بازه رد شوند
خواندن از جایی که دادهٔ زنده شروع می‌شودpredicate روی بازهٔ clustering پس از ناحیهٔ حذف‌شدههرگز tombstoneها را اسکن نمی‌کندبه مرز معلوم نیاز دارد
صف را جابه‌جا کنیدیک broker به‌جای جدولابزار درستمهاجرت

یک node بیش از hint window خاموش بود ​

نشانه: یک node پس از پنج ساعت برمی‌گردد؛ خواندن با ONE از آن دادهٔ کهنه برمی‌گرداند؛ هیچ خطایی دیده نمی‌شود. علت: hintها پس از max_hint_window (سه ساعت) متوقف شده‌اند.

text
     Runbook
1    node back up, gossip shows UN
2    downtime > max_hint_window ? yes -> repair this node now: nodetool repair (or let the scheduler prioritise it)
3    downtime > gc_grace_seconds ? yes -> do not repair: wipe data and replace/rebootstrap the node instead
4    until repair finishes, read at LOCAL_QUORUM so blocking read repair covers hot keys

کلاینت‌های آفلاین رکوردهای حذف‌شده را زنده می‌کنند ​

نشانه: سندهایی که در وب حذف شده‌اند پس از همگام‌شدن یک گوشی دوباره پیدا می‌شوند. علت: hard delete و polling با updated_at، یا ردیف‌های soft-deleted که پیش از همگام‌شدن همهٔ کلاینت‌ها prune شده‌اند. راه‌حل: tombstone در payload همگام‌سازی، prune پس از دورهٔ مهلت، و قاعده‌ای سخت برای کلاینت‌های قدیمی‌تر از دورهٔ مهلت.

sql
-- PostgreSQL: soft delete as a tombstone, live-row index, batched GC
CREATE TABLE documents (
    id          uuid PRIMARY KEY,
    title       text NOT NULL,
    payload     jsonb,
    version     integer NOT NULL DEFAULT 1,
    sync_bucket smallint NOT NULL,
    updated_at  timestamptz NOT NULL DEFAULT now(),
    deleted_at  timestamptz            -- NULL = live, NOT NULL = tombstone
);
CREATE INDEX documents_live_idx ON documents (sync_bucket, id) WHERE deleted_at IS NULL;
CREATE INDEX documents_tombstone_age_idx ON documents (deleted_at) WHERE deleted_at IS NOT NULL;

-- delete = write a tombstone; strip the payload now if erasure requires it
UPDATE documents SET deleted_at = now(), payload = NULL, version = version + 1 WHERE id = $1;

-- GC: remove tombstones older than the grace period, 5000 at a time (repeat until 0 rows)
DELETE FROM documents
WHERE id IN (
    SELECT id FROM documents
    WHERE deleted_at < now() - interval '30 days'
    ORDER BY deleted_at
    LIMIT 5000
    FOR UPDATE SKIP LOCKED
);

-- bucket hashes for the sync endpoint (tombstones included)
SELECT sync_bucket,
       encode(sha256(convert_to(string_agg(id::text || ':' || version || ':' ||
              (deleted_at IS NOT NULL)::int, E'\n' ORDER BY id::text), 'UTF8')), 'hex') AS content_hash
FROM documents
GROUP BY sync_bucket
ORDER BY sync_bucket;

هش bucket در SQL فقط ایده را نشان می‌دهد (پیشوند 0x00 در RFC 6962 را ندارد، پس بایت‌به‌بایت با MerkleIndex::leafHash یکی نیست)؛ کد Laravel نسخه‌ای است که باید منتشر شود. در Go با database/sql همان دستور GC در یک حلقه اجرا می‌شود تا RowsAffected() صفر برگرداند.

یک مصرف‌کنندهٔ Kafka حذفی را از دست داد ​

نشانه: کشی که از یک topic فشرده‌شده بازسازی شده هنوز کاربرانی را دارد که حذف شده‌اند. علت: بازسازی بیش از delete.retention.ms طول کشیده، پس tombstone پیش از رسیدن مصرف‌کننده پاک شده، آن هم بعد از این‌که مصرف‌کننده مقدار قدیمی را خوانده بود.

راه‌حلچطورمزیتهزینه / محدودیت
نگهداری طولانی‌تر tombstonedelete.retention.ms بالاتر از طولانی‌ترین بازپخش کامل (مثلاً ۷ روز)سادهtombstone بیشتری نگه داشته می‌شود
snapshot به‌اضافهٔ دنبالهاز یک snapshot بازسازی کنید، بعد از offset آن مصرف کنیدبازسازی سریعمدیریت snapshot
هشدار lagوقتی lag زمانی مصرف‌کنندهٔ در حال بازسازی به delete.retention.ms نزدیک شد هشدار دهیدهشدار زودهنگامفقط پایش

اثبات این‌که یک رکورد در audit log هست ​

از درخت RFC 6962 استفاده کنید: هر رکورد audit را به‌عنوان برگ اضافه کنید، ریشه (و اندازه) را روزانه جایی منتشر کنید که نتوانید بی‌صدا ویرایشش کنید، و به حسابرس برای رکوردها inclusion proof و بین ریشه‌های منتشرشده consistency proof بدهید. بستهٔ merkle دقیقاً همین را انجام می‌دهد؛ golang.org/x/mod/sumdb/tlog پیاده‌سازی تولیدی پشت پایگاه checksum در Go است.

انتخاب ​

کدام سازوکار همگرایی برای کدام واگرایی ​

وضعیتسازوکارتکنیک اضافهدلیل
rolling restart، نگهداری کوتاهHinted handoffmax_hint_window را بالاتر از طولانی‌ترین قطعی برنامه‌ریزی‌شده نگه داریدارزان، در چند دقیقه بازپخش می‌شود
کلیدهای داغ با خواندن QUORUMBlocking read repairبا LOCAL_QUORUM بخوانیدآنچه کاربر می‌بیند را مجانی هم‌گام می‌کند
دادهٔ سرد، آرشیو، هر چیز حذف‌شدهترمیم anti-entropy زمان‌بندی‌شدهincremental روزانه، full هفتگی، درون gc_grace_secondsتنها مسیری که به دادهٔ خوانده‌نشده می‌رسد
node خاموش بیش از hint windowrepair هدفمند همان nodeدر Reaper یا Auto Repair اولویت بدهیدhint دیگر پوشش نمی‌دهد
node خاموش بیش از gc_grace_secondsجایگزینی یا bootstrap دوباره، هرگز پیوستن دوبارهcheck_data_resurrectionپیوستن دوباره حذف‌ها را زنده می‌کند
افزایش replication factor، افزودن nodeFull repairnodetool repair -fullreplicaهای تازه خالی شروع می‌کنند
شک به خرابی دیسکFull repair یا اول --validateRiak: ساخت دوبارهٔ هفتگی درخت همین کار را می‌کندincremental هرگز دادهٔ repaired را دوباره بررسی نمی‌کند
کلاینت‌های گوشی یا مرورگرهمگام‌سازی bucket مرکلی یا changes feedtombstone در payload، resync پس از مهلتکلاینت‌ها می‌توانند هفته‌ها آفلاین باشند
مدرک عمومی و فقط‌افزودنیدرخت RFC 6962 با ریشهٔ منتشرشدهinclusion + consistency proofقابل وارسی توسط بیرونی‌ها
فایل‌های بزرگ بین سرورهاrsync--checksum وقتی timestampها دروغ می‌گویندrolling checksum بلاک‌های جابه‌جاشده را پیدا می‌کند

کدام راهبرد حذف ​

دادهراهبرد حذفمهلت / نگهداریچرا
ردیف‌های Cassandra که برنامه حذفشان می‌کندtombstone، در درشت‌ترین سطح ممکنgc_grace_seconds = چرخهٔ repair + حاشیه (پیش‌فرض ۱۰ روز)درستی در برابر خرابی replica
دادهٔ Cassandra که فقط منقضی می‌شودTTL + TWCSgc_grace_seconds کمتر امن است اگر هرگز حذف یا به‌روز نشودهر replica خودش منقضی می‌کند
دادهٔ شبیه صفنه در Cassandra: یک brokerنداردسربار tombstone
topic فشرده‌شده در Kafkatombstone با مقدار nulldelete.retention.ms بالاتر از طولانی‌ترین بازپخشبازسازی‌ها باید حذف‌ها را ببینند
ردیف‌های SQL که کلاینت‌ها یا سیستم‌های دیگر کپی می‌کنندsoft delete + pruneبلندتر از طولانی‌ترین کلاینت آفلاینحذف‌ها باید به کپی‌ها برسند
ردیف‌های SQL که کسی کپی نمی‌کندHard deleteنداردساده‌ترین؛ چیزی برای انتشار نیست
دادهٔ شخصی تحت قواعد پاک‌سازیtombstone با payload خالی‌شده همین حالا، prune ردیف بعداًکوتاه، مستندمحتوا اکنون پاک، id بعداً

در معماری: از یک پردازه تا سیستم توزیع‌شده ​

ترمیم و tombstone به این دلیل هستند که کپی وجود دارد. هر گام زیر نوع تازه‌ای از کپی اضافه می‌کند و هر کپی راهی لازم دارد تا از نوشتن‌ها و حذف‌هایی که جا انداخته باخبر شود.

Monolith: یک پردازه، یک دیتابیس ​

یک دیتابیس PostgreSQL با نوشتن هم‌گام replicaی واگرا ندارد، پس anti-entropy هم ندارد. اما به‌محض این‌که چیزی بیرون از دیتابیس کپی نگه دارد ارزش دارد به حذف فکر کنید: کش مرورگر، خروجی CSV، search index که با cron job به‌روز می‌شود. مثال: اپ Laravel با قابلیت «سطل زباله» برای undo از SoftDeletes و برای خالی‌کردن سطل پس از ۳۰ روز از Prunable استفاده می‌کند؛ هیچ‌چیز دیگری جدول را کپی نمی‌کند، پس DELETE سخت هم درست بود. dead tupleهای MVCC در PostgreSQL که VACUUM پاکشان می‌کند tombstoneهای درونی خود دیتابیس‌اند (MVCC, VACUUM & Bloat).

Modular monolith: مرزها بدون شبکه ​

ماژول‌هایی که read model خودشان را دارند (ماژول جست‌وجو، ماژول گزارش) داده را از ماژول مالک کپی می‌کنند. اگر با کوئری‌های «تغییرکرده از» تغذیه شوند، hard delete در مالک برایشان نامرئی است. مثال: ماژول صورت‌حساب فاکتورها را soft delete می‌کند و رویداد درون‌پردازه‌ای InvoiceDeleted منتشر می‌کند؛ ماژول گزارش با این رویداد ردیفش را حذف می‌کند و هر هفته هم یک reconciliation اجرا می‌کند که هش ماهانهٔ شناسه‌های فاکتور را با ماژول صورت‌حساب مقایسه می‌کند (مقایسهٔ مرکلی دوسطحی) تا رویدادهای ازدست‌رفته را بگیرد.

Microservices: هر کپی یک مسیر حذف لازم دارد ​

هر سرویس صاحب داده‌اش است و سرویس‌های دیگر projection نگه می‌دارند. حذف‌ها باید به شکل رویداد سفر کنند (outbox، Transactional Outbox) و هر مصرف‌کننده باید حذف را آن‌قدر نگه دارد که به replicaها و کش‌های خودش برسد. مثال:

text
     users-service                     Kafka topic users (compacted)            search-service, mail-service
1    DELETE user 7 -> outbox row
2    relay publishes key=7, value=null  ->  tombstone at offset 9001
3                                                                               search: remove doc 7; mail: unsubscribe 7
4    nightly: each consumer sends per-bucket hashes of its user ids to users-service /reconcile
5    users-service returns divergent buckets -> consumer fixes them (catches lost events and zombies)

گام reconciliation همان anti-entropy بین سرویس‌هاست. همین است که «eventually consistent» را وقتی یک رویداد گم شده، یک مصرف‌کننده از snapshot قدیمی بازسازی شده یا باگی پیام‌ها را رد کرده، درست نگه می‌دارد.

دادهٔ توزیع‌شده: replica، کش، region ​

storeهای بی‌رهبر (Cassandra، ScyllaDB، Riak) هر سه مسیر و یک برنامهٔ repair درون gc_grace_seconds لازم دارند؛ Cassandra چند regionی repair بین datacenterها (-dc، -dcpar، -local) و hintهایی را اضافه می‌کند که بین regionها کندترند (max_hints_delivery_threads). storeهای رهبرمحور (PostgreSQL، MySQL) log را به replicaها می‌فرستند و برای کار عادی به ترمیم مرکلی نیاز ندارند، اما ابزارهایی که replicaها را وارسی می‌کنند checksum تکه‌هایی از جدول‌ها را مقایسه می‌کنند؛ همان ایده. کش‌ها جلوی هر storeی حذف را به شکل invalidation، یا یک مدخل منفی با TTL، لازم دارند وگرنه دادهٔ حذف‌شده را تا انقضا سرو می‌کنند (Caching). storeهای مبتنی بر CRDT حذف را به عملیات مجموعه با سازوکار tombstone یا causal context خودشان تبدیل می‌کنند (CRDTs).

مسیر مقیاس: 1x، 10x، 100x ​

مقیاسچه چیزی عوض می‌شودطراحی repair و حذف
1x: یک دیتابیس، چند کلاینتکپی نادر استsoft delete جایی که کپی هست؛ prune با model:prune
10x: replica، کش، search index، کلاینت موبایلکپی‌های زیاد با تأخیر مستقلحذف به شکل رویداد؛ همگام‌سازی bucket مرکلی برای کلاینت‌ها؛ کارهای reconciliation
100x: خوشهٔ بی‌رهبر، چند regionreplicaها روزانه واگرا می‌شوندزمان‌بند repair (Reaper / Auto Repair)، subrange repair، هشدار سن repair در برابر gc_grace_seconds، مدل داده بدون چرخش tombstone شبیه صف

آزمایشگاه: اثبات‌ها، هزینهٔ diff و سه سناریوی حذف ​

بخش A روی ماشین شما در کمتر از یک ثانیه اجرا می‌شود (یک برنامهٔ Go تک‌پردازه‌ای؛ خروجی زیر از یک اجرای واقعی است). بخش‌های B و C به یک خوشهٔ Cassandra و یک اپ Laravel نیاز دارند و به شکل فرمان با خروجی موردانتظار نوشته شده‌اند؛ «خروجی موردانتظار؛ اجرا نشده».

A1. تست‌ها و راه‌انداز آزمایشگاه را اجرا کنید.

bash
cd docs/snippets/system-design/merkle-trees-anti-entropy/go
go test ./...
go run ./cmd/aesim
text
ok   academy/merkle-trees-anti-entropy/antientropy
ok   academy/merkle-trees-anti-entropy/before
ok   academy/merkle-trees-anti-entropy/kvsim
ok   academy/merkle-trees-anti-entropy/merkle
== 1. RFC 6962 tree: root, inclusion proof, consistency proof
leaves=1000000 root=9b6f9226d33c8d01...
inclusion proof for leaf 123456: 20 hashes (640 bytes), valid=true
consistency proof 600000 -> 1000000: 15 hashes, valid=true
== 2. one divergent key among 100000: cost by branching factor
fanout  depth  buckets  rounds  hashes  streamed
2       4      16       5       9       6110
2       16     65536    17      33      2
4       8      65536    9       33      2
16      4      65536    5       65      2
256     2      65536    3       513     2
65536   1      65536    2       65537   2
== 3. replica c misses a delete (down 4h, hint window 3h)
hard delete                              hints_dropped=1 purged=0 streamed=2 -> read found=true "3 items"
tombstone, gc_grace 10d, back after 5h   hints_dropped=1 purged=0 streamed=2 -> read found=false ""
tombstone, gc_grace 1d, back after 2d    hints_dropped=1 purged=2 streamed=2 -> read found=true "3 items"

این خروجی کل فصل به عدد است: logی با یک میلیون برگ عضویت را با ۶۴۰ بایت ثابت می‌کند؛ یک تفاوت تک‌کلیدی بسته به شکل درخت بین ۹ تا ۶۵٬۵۳۷ مقایسهٔ هش و ۲ تا ۶٬۱۱۰ کلید stream‌شده هزینه دارد؛ و سناریوی حذف دو حالت مستندات Cassandra را بازتولید می‌کند: «حذف بدون tombstone» و «tombstone که پیش از repair منقضی شد».

A2. عمداً خرابش کنید. در kvsim_test.go مقدار GCGrace را در TestTombstoneSurvivesRepair به 1 * hour تغییر دهید و go test ./kvsim/ -run Survives -v را اجرا کنید: تست حالا شکست می‌خورد، چون tombstone در طول قطعی پاک شده است. در TestRepairCostFollowsTheDifference مقدار Fanout: 16, Depth: 2 را به Fanout: 2, Depth: 1 تغییر دهید: تعداد stream‌شده به هزاران می‌پرد (over-streaming).

B. Cassandra: یک زامبی در چند فرمان (خروجی موردانتظار؛ اجرا نشده). سه node، RF = 3، و gc_grace_seconds فقط برای آزمایش پایین آورده شده.

bash
cqlsh -e "CREATE KEYSPACE lab WITH replication = {'class':'SimpleStrategy','replication_factor':3};
          CREATE TABLE lab.t (id int PRIMARY KEY, v text) WITH gc_grace_seconds = 60;
          INSERT INTO lab.t (id, v) VALUES (1, 'alive');"
nodetool -h node1 disablehandoff; nodetool -h node2 disablehandoff  # no hints: simulate an outage past max_hint_window
nodetool -h node3 disablegossip && nodetool -h node3 disablebinary   # node3 stops receiving writes
cqlsh -e "CONSISTENCY QUORUM; DELETE FROM lab.t WHERE id = 1;"
sleep 120; nodetool -h node1 flush lab t; nodetool -h node1 compact lab t; nodetool -h node2 flush lab t; nodetool -h node2 compact lab t
nodetool -h node3 enablegossip && nodetool -h node3 enablebinary
nodetool -h node3 repair --full lab t
cqlsh -e "CONSISTENCY ALL; SELECT * FROM lab.t WHERE id = 1;"
text
 id | v
----+-------
  1 | alive          <- expected: the deleted row is back (a zombie)

بعد روی node1 و node2 دوباره nodetool enablehandoff را اجرا کنید. آزمایش را با gc_grace_seconds = 864000 پیش‌فرض تکرار کنید: select آخر (0 rows) برمی‌گرداند، چون tombstone هنوز بود و repair آن را به node3 stream کرد.

C. Laravel: tombstone در API همگام‌سازی (خروجی موردانتظار؛ اجرا نشده).

bash
php artisan migrate
php artisan tinker --execute="\$d = App\Models\Document::create(['title' => 'note']); \$d->delete(); echo \$d->id;"
curl -s localhost:8000/api/sync/root -H "Authorization: Bearer $TOKEN"
# {"root":"5f1c...","buckets":256,"tombstone_grace_days":30,"server_time":"2026-11-26T10:00:00+00:00"}
curl -s -X POST localhost:8000/api/sync/diff -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
     -d '{"last_synced_at":"2026-11-20T00:00:00Z","buckets":[ ...256 hashes of an empty client... ]}'
# {"divergent_buckets":[173],"rows":[{"id":"...","version":1,"deleted":true,"title":null,"payload":null}],...}
php artisan model:prune --pretend
# expected: 0 Document records will be pruned (the tombstone is younger than 30 days)
curl -s -X POST localhost:8000/api/sync/diff ... -d '{"last_synced_at":"2026-09-01T00:00:00Z", ...}'
# HTTP 409 {"resync_required":true}

D. اثبات با دست. با هشت ورودی آزمون CT در merkle_test.go، مسیر حسابرسی اندیس ۵ را با tree.InclusionProof(5, 8) بگیرید و چهار گام timeline اثبات عضویت را با هش‌های چاپ‌شده روی کاغذ طی کنید؛ نتیجه باید 5dc9da79a70659a9... باشد.

بدفهمی‌های رایج ​

باورواقعیت
خواندن و نوشتن quorum ترمیم را غیرلازم می‌کندquorum داده را به replicaهایی که جا انداخته‌اند کپی نمی‌کند؛ فقط repair همگرایی و انتشار حذف را تضمین می‌کند
درخت مرکل داده را ارزان مقایسه می‌کندمقایسهٔ شبکه‌ای را ارزان می‌کند؛ ساختنش همهٔ داده را می‌خواند (validation compaction)
read repair همهٔ replicaهای یک کلید را درست می‌کندفقط replicaهایی که خواندن سراغشان رفت؛ در ONE/LOCAL_ONE هیچ
read_repair_chance ترمیم پس‌زمینهٔ مجانی می‌دهددر Cassandra 4.0 حذف شد؛ هرگز به دادهٔ سرد نمی‌رسید
hinted handoff nodeی را که برمی‌گردد سازگار می‌کندفقط برای قطعی کوتاه‌تر از max_hint_window (سه ساعت) با فایل‌های hint سالم
حذف داده فضا آزاد می‌کند و خواندن را سریع می‌کندحذف یک نوشتن است؛ فضا پس از compaction و گذشت gc_grace_seconds برمی‌گردد
کم‌کردن gc_grace_seconds مشکل tombstone را حل می‌کندسربار tombstone را با خطر زامبی عوض می‌کند؛ به‌جایش مدل داده را درست کنید
TTL جلوی tombstone را می‌گیردcellهای منقضی tombstone می‌شوند؛ TTL + TWCS اجازه می‌دهد کل SSTableها منقضی شوند
incremental repair همهٔ نیاز استدادهٔ repaired هرگز دوباره بررسی نمی‌شود؛ full repair را دوره‌ای اجرا کنید
nodetool repair کل خوشه را repair می‌کندبازه‌های یک node را repair می‌کند؛ -pr روی همهٔ nodeها یا یک زمان‌بند لازم است
soft delete فقط برای undo استهمان tombstoneی است که هر کپی جدول برای باخبرشدن از حذف‌ها لازم دارد
CouchDB replication مرکلی استیک changes feed با checkpoint و _revs_diff است
یک inclusion proof صادق‌بودن log را ثابت می‌کندفقط نسبت به ریشه‌ای که به آن اعتماد دارید؛ در برابر split view به consistency proof و gossip کردن tree headها نیاز است

چکیده (Cheat sheet) ​

موضوعبه خاطر بسپارید
درخت مرکلبرگ‌ها داده را هش می‌کنند، گره‌ها فرزندان را، ریشه همه را خلاصه می‌کند؛ از بالا به پایین مقایسه کنید
هش در RFC 6962برگ `SHA-256(0x00
اندازهٔ اثباتinclusion برابر ceil(log2 n)، consistency برابر ceil(log2 n) + 1؛ یک میلیون برگ: ۲۰ هش
هزینهٔ diffیکسان: ۱ هش؛ k تفاوت: حدود 1 + k * b * d هش، d + 1 دور
وضوحتعداد کلید در هر برگ over-streaming را تعیین می‌کند؛ Cassandra: repair_session_space، subrange repair
سه مسیرhint (نوشتن)، read repair (خواندن)، anti-entropy (پس‌زمینه)؛ فقط آخری تضمین است
Hintپیش‌فرض max_hint_window سه ساعت؛ قطعی طولانی‌تر یعنی repair همان node
Read repairdigest request، ناهمخوانی، خواندن کامل، تازه‌ترین برنده، پیش‌فرض BLOCKING، NONE برای اتمی‌بودن batch
repair در Cassandraپیش‌فرض incremental، --full دوره‌ای، -pr برای هر node، Reaper یا Auto Repair، --preview، --validate
قاعدههر replica را درون gc_grace_seconds repair کنید (پیش‌فرض 864000 = ۱۰ روز)
حدهای tombstoneهشدار 1000، شکست 100000 (TombstoneOverwhelmingException)
انواع tombstonecell، row، range، partition، TTL؛ در درشت‌ترین سطح حذف کنید
Kafkaمقدار null = tombstone؛ پیش‌فرض delete.retention.ms یک روز؛ بازسازی کند حذف‌ها را از دست می‌دهد
LaravelSoftDeletes = tombstone، withTrashed() در همگام‌سازی، Prunable + model:prune = GC پس از مهلت
کلاینت‌هاحذف‌ها را در همگام‌سازی بگنجانید؛ کلاینت‌های قدیمی‌تر از مهلت را رد کنید (409)

خودآزمایی: پرسش و پاسخ ​

نمایش:
  • حیاتی تقریباً در هر مصاحبه پرسیده می‌شود
  • مهم پرتکرار؛ در سطح senior انتظار می‌رود
  • تکمیلی عمق بیشتر؛ تمایز ایجاد می‌کند

۱ — دو replica هرکدام ۵۰ میلیون کلید در درختی با 65,536 برگ دارند و جز یک کلید یکسان‌اند. با fan-out برابر ۱۶ چند هش مقایسه می‌شود و تقریباً چند کلید stream می‌شود؟ تکمیلی ​

پاسخ

پاسخ: 65,536 = 16^4، پس عمق ۴: یک ریشه + ۱۶ در هر سطح × ۴ سطح = ۶۵ هش در ۵ دور. یک برگ فرق دارد که حدود 50,000,000 / 65,536، یعنی تقریباً ۷۶۰ کلید، دارد و همان‌ها stream می‌شوند (over-streaming)، نه ۵۰ میلیون.

۲ — چرا RFC 6962 به برگ‌ها پیشوند 0x00 و به گره‌ها 0x01 می‌دهد؟ تکمیلی ​

پاسخ

پاسخ: جداسازی دامنه. بدون آن، ۶۴ بایت دو هش فرزند را می‌شد به‌عنوان دادهٔ یک برگ جا زد و برای فهرستی دیگر همان ریشه را ساخت (second preimage). RFC می‌گوید: "This domain separation is required to give second preimage resistance."

۳ — مرورگری signed tree head برای اندازهٔ ۸ دارد و audit path [h4, h(6-7), h(0-3)] را برای برگ ۵ می‌گیرد. محاسبه‌های هش را بنویسید. تکمیلی ​

پاسخ

پاسخ: r = H(0x01 || h4 || leaf5)، سپس r = H(0x01 || r || h(6-7))، سپس r = H(0x01 || h(0-3) || r)؛ و مقایسه با ریشهٔ امضاشده. اندیس ۵ فرد است (هم‌سایه در چپ)، ۲ زوج است (هم‌سایه در راست)، ۱ فرد است (هم‌سایه در چپ).

۴ — یک node در Cassandra پنج ساعت خاموش بوده و hint با پیش‌فرض‌ها روشن است. کدام نوشتن‌ها را برای همیشه از دست داده و چه چیزی درستشان می‌کند؟ مهم ​

پاسخ

پاسخ: نوشتن‌های پس از سه ساعت اول (max_hint_window = 3h): coordinatorها دیگر hint نساختند. hintها سه ساعت اول را بازپخش می‌کنند. بقیه برای کلیدهایی که با QUORUM/LOCAL_QUORUM خوانده می‌شوند با read repair درست می‌شوند و به‌طور کامل فقط با ترمیم anti-entropy همان node.

۵ — چرا read repair با LOCAL_QUORUM حتی روی جدول پرخواندن جای repair زمان‌بندی‌شده را نمی‌گیرد؟ حیاتی ​

پاسخ

پاسخ: فقط کلیدهایی را که خوانده می‌شوند، و فقط روی replicaهایی که آن خواندن سراغشان رفت، ترمیم می‌کند. کلیدهای سرد و حذف کلیدهایی که کسی نمی‌خواند هرگز ترمیم نمی‌شوند و پس از gc_grace_seconds tombstoneشان پاک می‌شود: زنده‌شدن داده.

۶ — توالی دقیقی را که یک حذف را در Cassandra به زامبی تبدیل می‌کند توصیف کنید. مهم ​

پاسخ

پاسخ: یک replica حذف را از دست می‌دهد (خاموش بیش از hint window)؛ replicaهای دیگر tombstone را به‌مدت gc_grace_seconds نگه می‌دارند، بعد compaction هم tombstone و هم دادهٔ زیرش را پاک می‌کند؛ replica با مقدار قدیمی برمی‌گردد؛ repair (یا read repair) داده را روی یک replica و هیچ را روی بقیه می‌بیند و داده را برمی‌گرداند.

۷ — تیم شما می‌خواهد به‌خاطر هشدارهای tombstone مقدار gc_grace_seconds یک جدول را از ۱۰ روز به یک ساعت کم کند. کی امن است؟ مهم ​

پاسخ

پاسخ: فقط وقتی هیچ replicaای نتواند یک حذف را بیش از یک ساعت از دست بدهد؛ در عمل یعنی از جدول هرگز صریحاً حذف یا به‌روزرسانی نمی‌شود و داده فقط با TTL منقضی می‌شود (هر replica مستقل منقضی می‌کند). وگرنه مدل را درست کنید (سطل زمانی، حذف بازه یا partition، TWCS).

۸ — اگر incremental repair هر روز اجرا می‌شود، چرا هنوز full repair لازم است؟ مهم ​

پاسخ

پاسخ: incremental repair داده را repaired علامت می‌زند و دیگر هرگز مقایسه‌اش نمی‌کند. خرابی دیسک، خطای اپراتور و باگ در دادهٔ از قبل repaired برایش نامرئی است؛ فقط full repair (یا --validate) مجموعهٔ repaired را دوباره بررسی می‌کند.

۹ — یک topic فشرده‌شده در Kafka مقدار delete.retention.ms برابر یک روز دارد. سرویسی کشش را از offset 0 بازسازی می‌کند که ۳۰ ساعت طول می‌کشد. چه چیزی ممکن است خراب شود؟ مهم ​

پاسخ

پاسخ: زود مقدار قدیمی کلید k را می‌خواند؛ tombstone کلید k (نوشته‌شده پس از آن مقدار) ۲۴ ساعت پس از نوشته‌شدن پاک می‌شود؛ مصرف‌کننده بعداً به آن offset می‌رسد و هرگز حذف را نمی‌بیند. کش k را برای همیشه نگه می‌دارد. delete.retention.ms را بالاتر از زمان بازپخش ببرید یا از snapshot بازسازی کنید.

۱۰ — یک اپ آفلاین‌محور ردیف‌های soft-deleted را ۳۰ روز نگه می‌دارد. گوشی‌ای پس از ۴۵ روز برمی‌گردد. API چه باید بکند و چرا؟ مهم ​

پاسخ

پاسخ: همگام‌سازی افزایشی را رد کند (در این صفحه: 409 resync_required) و کلاینت را وادار به دانلود نسخهٔ تازه کند. tombstoneهای سندهایی که بیش از ۳۰ روز پیش حذف شده‌اند prune شده‌اند، پس کپی‌های گوشی از آن‌ها از سندهایی که سرور هرگز دریافت نکرده قابل‌تشخیص نیستند؛ همگام‌کردنشان دادهٔ حذف‌شده را زنده می‌کند.

۱۱ — آیا CouchDB replication پروتکلی مرکلی است؟ حذف‌ها را چطور منتقل می‌کند؟ تکمیلی ​

پاسخ

پاسخ: نه. changes feed مبدأ را از یک checkpoint می‌خواند، با _revs_diff از مقصد می‌پرسد کدام revisionها را ندارد، آن‌ها را کپی می‌کند و checkpoint را ذخیره می‌کند. حذف یک revision تازه با _deleted: true است، پس مثل هر revision دیگری replicate می‌شود تا وقتی _purge آن را بردارد.

۱۲ — چرا Riak درخت‌های هش AAE را با این‌که با هر نوشتن به‌روز می‌شوند، دوره‌ای از نو می‌سازد؟ تکمیلی ​

پاسخ

پاسخ: درختی که با نوشتن به‌روز می‌شود آنچه را نوشته شده نشان می‌دهد، نه آنچه را اکنون روی دیسک است. ساختن دوبارهٔ "all hash trees from on-disk key/value data" (پیش‌فرض هفتگی) خرابی خاموش دادهٔ ذخیره‌شده را کشف می‌کند که نگهداری افزایشی درخت هرگز نمی‌فهمد.

واژه‌نامه (Glossary) ​

واژهمعنا
درخت مرکل (Merkle tree / hash tree)درختی که برگ‌هایش بلوک‌های داده و گره‌های داخلی‌اش فرزندانشان را هش می‌کنند
هش ریشه (Root hash)هش بالای درخت؛ ریشهٔ برابر یعنی محتوای برابر (با احتمال بسیار بالا)
برگ (Leaf)گرهٔ پایینی: هش یک قلم یا یک بازهٔ کلید
ضریب انشعاب (Branching factor / fan-out)تعداد فرزند هر گرهٔ داخلی؛ بیشتر یعنی دور کمتر و هش بیشتر در هر دور
عمق (Depth)سطح‌های زیر ریشه؛ در درخت کامل برگ‌ها = fan-out^depth
وضوح (Resolution)تعداد کلید در هر برگ؛ وضوح کم یعنی over-streaming
اثبات عضویت (Inclusion proof / audit path / audit proof)هش‌های هم‌سایه از یک برگ تا ریشه که بودن برگ را در درخت ثابت می‌کنند
مسیر احراز (Authentication path)نامی که مرکل در ۱۹۷۹ برای audit path گذاشت
اثبات سازگاری (Consistency proof)هش‌هایی که ثابت می‌کنند درخت کوچک‌تر پیشوند درخت بزرگ‌تر است (رشد فقط‌افزودنی)
Signed Tree Head (STH)ریشه و اندازهٔ امضاشدهٔ یک CT log
Certificate Transparencylogهای عمومی و فقط‌افزودنی گواهی‌های TLS (RFC 6962، RFC 9162)
RFC 6962RFC آزمایشی ۲۰۱۳ که Merkle Tree Hash در CT، audit path و consistency proof را تعریف می‌کند
پیش‌تصویر دوم (Second preimage)ورودی دیگری با همان هش؛ در RFC 6962 با پیشوندهای 0x00/0x01 جلویش گرفته می‌شود
آدرس‌دهی محتوایی (Content addressing)نام‌گذاری داده با هش محتوای آن
شیء Git (Git object)blob، tree، commit یا tag ذخیره‌شده زیر هش خود؛ tree هش فرزندان را فهرست می‌کند
ضدآنتروپی (Anti-entropy)مقایسه و آشتی پس‌زمینهٔ replicaها (Demers ۱۹۸۷)
ضدآنتروپی فعال (Active anti-entropy, AAE)anti-entropy پیوستهٔ Riak با درخت‌های هش ماندگار که با نوشتن به‌روز می‌شوند
ترمیم (Repair)anti-entropy اپراتورمحور Cassandra: درخت مرکل برای هر token range، stream تفاوت‌ها
ترمیم کامل (Full repair)همهٔ دادهٔ بازه‌ها را مقایسه می‌کند (nodetool repair --full)
ترمیم افزایشی (Incremental repair)فقط دادهٔ unrepaired را مقایسه و بعد repaired علامت می‌زند (پیش‌فرض)
SSTable ترمیم‌شده (Repaired SSTable)SSTableی که با یک incremental repair کامل‌شده پوشش داده شده؛ جدا compact می‌شود
SSTable ترمیم‌نشده (Unrepaired SSTable)SSTable با داده‌ای که هنوز incremental repair نشده
ضدفشرده‌سازی (Anticompaction)بازنویسی SSTableها برای جداکردن بازه‌های repaired پس از یک repair
Validation compactionخواندن داده که هنگام repair در Cassandra درخت مرکل را می‌سازد
ترمیم زیربازه (Subrange repair)repair یک token range با -st/-et برای وضوح بیشتر و واحدهای کوچک‌تر
بازهٔ اصلی (Primary range, -pr)بازه‌هایی که node اولین replica آن‌هاست؛ روی همهٔ nodeها repairشان کنید تا حلقه یک بار پوشش داده شود
nodetool repairابزار خط فرمان Cassandra برای repair؛ گزینه‌های --full، -pr، -st/-et، --preview، --validate، -dc، -seq، -j
Reaperزمان‌بند متمرکز و حالت‌دار repair برای Cassandra
Auto Repairزمان‌بند repair درونی Cassandra (CEP-37، نسخهٔ 6.0، backport به 5.0.8)
ترمیم سطح ردیف (Row-level repair)repair در ScyllaDB که به‌جای تبادل درخت از ردیف‌ها checksum می‌گیرد و مجموعه‌ها را آشتی می‌دهد
بازهٔ واگرا (Divergent range)token rangeی که هش‌هایش بین replicaها فرق دارد
Over-streamingstream کردن دادهٔ بیشتر از آنچه عوض شده، چون یک برگ کلیدهای زیادی را پوشش می‌دهد
ترمیم هنگام خواندن (Read repair)درست‌کردن replicaهای کهنه هنگام یک خواندن در صورت digest mismatch
درخواست چکیده (Digest request)خواندنی که فقط هش داده را برمی‌گرداند
ناهمخوانی چکیده (Digest mismatch)digest replicaها با هش دادهٔ کامل فرق دارد؛ خواندن کامل و repair را راه می‌اندازد
Blocking read repairخواندن منتظر می‌ماند تا نوشتن‌های repair به سطح سازگاری برسند (read_repair = 'BLOCKING')
Monotonic quorum readsخواندن quorum بعدی هرگز چیزی قدیمی‌تر از خواندن قبلی برنمی‌گرداند
read_repair_chanceاحتمال read repair پس‌زمینه پیش از 4.0؛ در Cassandra 4.0 حذف شد
Hinted handoffcoordinator نوشتن‌ها را برای replica خاموش نگه می‌دارد و بعداً بازپخش می‌کند
پنجرهٔ hint (Hint window)max_hint_window: مدتی که برای میزبان خاموش hint ساخته می‌شود (پیش‌فرض سه ساعت)
Sloppy quorumنوشتن روی N node سالم اول، نه لزوماً replicaهای اصلی کلید (Dynamo)
سنگ‌قبر (Tombstone / delete marker)رکوردی با timestamp که می‌گوید مقداری حذف شده؛ مثل داده تکثیر می‌شود
گواهی مرگ (Death certificate)نام tombstone در مقالهٔ Demers و همکاران (۱۹۸۷)
زنده‌شدن داده (Resurrection)برگشتن دادهٔ حذف‌شده چون یک replica حذف را از دست داده
دادهٔ زامبی (Zombie data)نامی که Cassandra برای دادهٔ زنده‌شده به کار می‌برد
gc_grace_secondsمدت نگهداری tombstone در هر جدول پیش از این‌که compaction بتواند پاکش کند (864000)
tombstone_warn_thresholdتعداد tombstone اسکن‌شده در یک کوئری پیش از هشدار (1000)
tombstone_failure_thresholdتعداد tombstone اسکن‌شده در یک کوئری پیش از توقف (100000)
TombstoneOverwhelmingExceptionخطای Cassandra وقتی کوئری از آستانهٔ شکست می‌گذرد
سنگ‌قبر بازه‌ای (Range tombstone)یک نشانگر که برشی از ردیف‌های یک partition را حذف می‌کند
سنگ‌قبر partition (Partition tombstone)یک نشانگر که کل یک partition را حذف می‌کند
سنگ‌قبر TTL (TTL tombstone)cell منقضی‌شده که مثل tombstone رفتار می‌شود
فشرده‌سازی (Compaction)ادغام SSTableها؛ دادهٔ پوشیده‌شده و tombstoneهای قدیمی را دور می‌ریزد
only_purge_repaired_tombstonesگزینهٔ compaction: tombstone را فقط از دادهٔ repaired پاک کن
sstableexpiredblockersابزاری که SSTableهای مانع دورریختن SSTableهای کاملاً منقضی را فهرست می‌کند
Kafka tombstoneرکوردی با key و مقدار null در یک topic فشرده‌شده
delete.retention.msمدت نگهداری tombstone در topicهای فشرده‌شدهٔ Kafka (پیش‌فرض یک روز)
Log compactionنگه‌داشتن آخرین مقدار هر key در Kafka
XDELفرمان Redis Streams که ورودی‌ها را برمی‌دارد؛ در درون حذف‌شده علامتشان می‌زند
CouchDB replicationreplication مبتنی بر changes feed با checkpoint و _revs_diff
_purgeendpoint در CouchDB که سندها (از جمله حذف‌شده‌ها) را برای همیشه برمی‌دارد
rsyncهمگام‌سازی فایل که فقط بلاک‌هایی را می‌فرستد که گیرنده ندارد
checksum غلتان (Rolling checksum)checksum ضعیف rsync که با هزینهٔ کم یک بایت‌یک بایت می‌لغزد
حذف نرم (Soft delete)نگه‌داشتن ردیف با مقدار deleted_at به‌جای برداشتن آن
SoftDeletestrait در Laravel که soft delete را برای مدل‌های Eloquent پیاده می‌کند
Prunable / MassPrunabletraitهای Laravel که مدل‌های منطبق با prunable() را حذف می‌کنند؛ نسخهٔ mass با یک کوئری
هرس (Pruning)حذف زمان‌بندی‌شدهٔ ردیف‌ها یا tombstoneهای منقضی (model:prune)
همگام‌سازی دوباره (Resync)دورریختن کپی کلاینت و دانلود دادهٔ تازه وقتی از دورهٔ مهلت قدیمی‌تر است

منابع (References) ​

ساخته‌شده توسط Morteza Negahi