فرض کنید کنار سامانهٔ جست‌وجو، جریانِ رویدادهایی داریم که می‌گوید هر شناسهٔ واژه چند بار درخواست شده است. برای تصمیمِ اولیه دربارهٔ واژه‌های پرتکرار، شاید خلاصه‌ای کوچک بخواهیم؛ اما اگر خلاصه برای واژه‌ای که هرگز نیامده عددی مثبت بدهد، چه معنایی دارد؟ در این درس، سازوکار Count-Min را با شمارنده‌های صحیح و نگاشت‌های کاملاً داده‌شده می‌سازیم تا جهتِ خطا، برخورد و ترتیبِ ادغام روشن باشد. مثال، سرویس جست‌وجوی شرکت یا اندازه‌گیری ترافیک واقعی نیست.

۱. فراوانیِ رویداد با فهرستِ سند یکی نیست

کارت‌های هویت‌دارِ بی‌نوشته در کنار ظرفِ رویدادهای تجمیع‌شده
تصویر مفهومی: کارت‌های هویت‌دارِ بی‌نوشته در کنار ظرفِ رویدادهای تجمیع‌شده؛ بدون مقیاس عددی و مستقل از نتایج اجرای کد.

واحدِ ورودی، یک رویدادِ شامل شناسه و وزنِ مثبت است. وزنِ دو یعنی دو رخدادِ هم‌نوع را یکجا اضافه می‌کنیم؛ نه دو سندِ متفاوت و نه دو کاربرِ یکتا. شناسه‌ها عددهای قراردادی‌اند و بیرونِ تابع به واژه معنا داده می‌شود. متن، زبان، نرمال‌سازی فارسی، هویتِ کاربر و زمانِ رخداد در این رابط وجود ندارند. بنابراین کمیتِ گزارش‌شده فقط مجموعِ وزنِ رویدادهای هر شناسه است.

در درسِ نمایهٔ معکوس و جست‌وجوی بولی، رابطهٔ واژه و شناسهٔ سند نگهداری می‌شد و تکرارِ واژه در یک سند، شناسهٔ تازه‌ای نمی‌ساخت. اینجا حتی شناسهٔ سند نداریم. Count-Min نمی‌تواند فهرستِ سندهای دارای واژه، محلِ رخداد یا نتیجهٔ AND و OR را بازگرداند. خلاصهٔ فراوانی می‌تواند کنارِ نمایه به کار رود، ولی جایِ اطلاعاتی را که ذخیره نکرده نمی‌گیرد.

مستنداتِ رسمی Redis نیز کاربردِ این ساختار را برآوردِ فراوانیِ عناصرِ جریان معرفی می‌کند. نمونه‌های محصول و تنظیمِ احتمالاتیِ آن صفحه، نتیجهٔ این آزمایش نیستند. برنامهٔ ما Redis، پایگاه داده یا شبکه را اجرا نمی‌کند. به‌جای پنهان کردنِ برخورد پشتِ هش، نگاشت‌های کوچک را صریح می‌گیریم تا بتوان هر خانه را با دست حساب کرد.

۲. شمارنده‌های مشترک و کمینهٔ ردیف‌ها

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

طرح یک جدولِ چندردیفی دارد. هر ردیف، برای هر شناسه یک شمارهٔ خانه تعیین می‌کند. با ورودِ رویداد، وزنش در همان خانهٔ هر ردیف جمع می‌شود. هنگامِ پرس‌وجوی شناسه، خانهٔ متناظرِ آن را از همهٔ ردیف‌ها می‌خوانیم و کمینه را برمی‌داریم. بخش‌های ۳ و ۴٫۱ مقالهٔ کورمود و موتوکریشنان ساختِ جدول و این پرسشِ نقطه‌ای را توضیح می‌دهند.

رابطِ sketch_term_streams(streams, bucket_maps, width) یک تا چهار بخشِ جریان می‌گیرد؛ هر بخش صفر تا هشت رویداد دارد. رویداد دقیقاً تاپلِ دوعضوی است: شناسه در دامنهٔ اعلام‌شده و وزنِ صحیحِ یک تا چهار. عرض یک تا چهار خانه و عمق یک تا سه ردیف است. هر ردیف دقیقاً برای یک تا شش شناسه خانه تعیین می‌کند و طولِ همهٔ ردیف‌ها برابر است.

همهٔ ظرف‌ها باید دقیقاً tuple و همهٔ عددها دقیقاً int باشند؛ بولی، زیرکلاسِ عدد و تبدیلِ ضمنیِ مولد پذیرفته نیستند. ردیفِ تکراری مجاز است، اما استقلالِ تازه‌ای ایجاد نمی‌کند. تمامِ شکل‌ها، نوع‌ها و کران‌ها پیش از ساختِ جدولِ شمارنده بررسی می‌شوند؛ ورودیِ نامعتبرِ انتهای بخشِ آخر هم نباید بخشی از محاسبه را آغاز کند. این سقف‌ها انتخابِ آموزشی‌اند، نه محدودیتِ عمومیِ Count-Min.

۳. برخورد، کرانِ بالا و واژهٔ هرگزندیده

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

اگر فراوانیِ واقعیِ شناسهٔ موردنظر را f بگیریم، هر خانهٔ خوانده‌شده شاملِ همان f به‌علاوهٔ وزنِ شناسه‌های دیگری است که به آن برخورد کرده‌اند. چون همهٔ وزن‌ها مثبت‌اند، سهمِ اضافی منفی نمی‌شود. پس کمینهٔ خانه‌ها نیز از f کمتر نیست. از طرفِ دیگر، هیچ خانه از وزنِ کلِ جریان بزرگ‌تر نیست. این استدلالِ جبری برای همین نگاشت‌های ثابت درست است و به فرضِ تصادفی بودن نیاز ندارد.

نمونهٔ دستی سه شناسه دارد. ردیفِ اول آن‌ها را به خانه‌های صفر، صفر و یک می‌فرستد؛ ردیفِ دوم به صفر، یک و یک. بخشِ اول وزنِ دو برای شناسهٔ صفر و سه برای شناسهٔ یک دارد؛ بخشِ دوم وزنِ چهار برای شناسهٔ دو. جدولِ ادغام‌شده ردیف‌های (5,4) و (2,7) می‌گیرد. فراوانی‌های واقعی دو، سه و چهارند، اما برآوردها دو، پنج و چهار می‌شوند.

حتی برآوردِ مثبت، شاهدِ قطعیِ دیده‌شدن نیست. اگر دو شناسه در همهٔ ردیف‌ها خانهٔ مشترک داشته باشند، رویدادهای یکی می‌توانند برای دیگری هم پاسخِ مثبت بسازند. یک ردیفِ بدونِ آلودگی، فراوانیِ دقیق را آشکار می‌کند؛ ولی وجودِ چنین ردیفی تضمین نشده است. پیش‌فیلتر بلوم و تأییدِ دقیق نیز مثبتِ احتمالی را از تصمیمِ قطعی جدا می‌کرد؛ تفاوتِ اینجا حفظِ وزن و شمارنده است، نه بیتِ عضویت.

قضیهٔ خطای احتمالاتیِ مقاله، انتخاب از خانوادهٔ هش با فرض‌های مشخص دارد. نگاشت‌های دست‌نویسِ ما چنین انتخابی نیستند؛ عددِ اطمینان یا کرانِ وابسته به epsilon و delta نمی‌دهیم. نسخهٔ نویسندگان، پیش‌چاپِ مورخ ۱۶ دسامبر ۲۰۰۳ است و ارجاعِ مجله به آوریلِ ۲۰۰۵ برمی‌گردد. در یک پاراگرافِ تعمیمِ عرض روی صفحهٔ چاپیِ هفت، صورتِ فرمول با ساختِ صفحهٔ شش ناسازگار است؛ این درس فرمولِ اندازه‌گذاریِ آن پاراگراف را به کار نمی‌برد.

۴. ادغامِ سازگار و مرجعِ مستقلِ پایتون

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

برای ترکیبِ بخش‌های جریان، خانه‌های متناظر را جمع می‌کنیم و سپس پرس‌وجو می‌زنیم. عرض، ترتیبِ ردیف‌ها و نگاشتِ شناسه‌ها باید یکسان باشند. قراردادِ CMS.MERGE سازگاریِ عرض و عمق را لازم می‌داند؛ در مدلِ عمومیِ نگاشتِ داده‌شده، معنای هر خانه نیز باید مشترک بماند. رابطِ ما فقط یک طرحِ مشترک برای همهٔ بخش‌ها می‌گیرد تا ادغامِ طرح‌های ناسازگار اصلاً ورودیِ مجاز نباشد.

جمعِ پاسخ‌ها با پرسش از جدولِ ادغام‌شده یکی نیست. در نمونهٔ دستی، برآوردِ شناسهٔ یک در بخشِ اول سه و در بخشِ دوم صفر است؛ جمعشان سه می‌شود. اما خانه‌های متناظر پس از ادغام پنج و هفت‌اند و کمینه پنج است. جمعِ برآوردهای محلی می‌تواند خودش یک کرانِ بالا باشد، ولی حالتِ Count-Min ساخته‌شده روی جریانِ کامل را بازسازی نمی‌کند. ابتدا باید بدانیم کدام کمیت را می‌خواهیم ترکیب کنیم.

کد کامل زیر فقط کتابخانهٔ استاندارد می‌خواهد. مسیرِ اصلی رویدادها را در جدول‌ها اضافه می‌کند؛ مرجعِ مستقل ابتدا جرمِ دقیقِ هر شناسه را می‌سازد و سپس وزنِ اعضای هر کلاسِ برخورد را جمع می‌زند. برای هر خانه نیز جمعِ گروهِ متناظر را مستقل می‌سازد. مرجع، تابعِ به‌روزرسانی یا تخصیصِ جدولِ مسیرِ اصلی را فراخوانی نمی‌کند؛ بنابراین اشتباهِ اندیس در یک مسیر لزوماً در انتظارِ مسیرِ دیگر تکرار نمی‌شود.

"""Own bounded Count-Min arithmetic with supplied deterministic bucket maps."""
from collections import Counter
from dataclasses import asdict, dataclass, FrozenInstanceError
from itertools import product
import json
import operator
import platform
import sys


@dataclass(frozen=True, slots=True)
class SketchReport:
    width: int
    bucket_maps: tuple
    shard_tables: tuple
    merged_table: tuple
    estimates: tuple
    total_weight: int


def _validated_shape(streams, bucket_maps, width):
    if type(width) is not int:
        raise TypeError('width must be an exact int')
    if not 1 <= width <= 4:
        raise ValueError('width must be in 1..4')
    if type(bucket_maps) is not tuple:
        raise TypeError('bucket_maps must be an exact tuple')
    if not 1 <= len(bucket_maps) <= 3:
        raise ValueError('supply 1..3 mapping rows')
    if any(type(row) is not tuple for row in bucket_maps):
        raise TypeError('mapping rows must be exact tuples')
    n = len(bucket_maps[0])
    if not 1 <= n <= 6 or any(len(row) != n for row in bucket_maps):
        raise ValueError('rows must have equal item count in 1..6')
    for row in bucket_maps:
        for bucket in row:
            if type(bucket) is not int:
                raise TypeError('bucket IDs must be exact ints')
            if not 0 <= bucket < width:
                raise ValueError('bucket ID outside declared width')
    if type(streams) is not tuple:
        raise TypeError('streams must be an exact tuple')
    if not 1 <= len(streams) <= 4:
        raise ValueError('supply 1..4 partitions')
    for stream in streams:
        if type(stream) is not tuple:
            raise TypeError('each partition must be an exact tuple')
        if len(stream) > 8:
            raise ValueError('at most 8 events per partition')
        for event in stream:
            if type(event) is not tuple:
                raise TypeError('events must be exact tuples')
            if len(event) != 2:
                raise ValueError('event must contain item ID and weight')
            item, weight = event
            if type(item) is not int or type(weight) is not int:
                raise TypeError('item and weight must be exact ints')
            if not 0 <= item < n or not 1 <= weight <= 4:
                raise ValueError('item outside map or nonpositive/excess weight')
    return n, len(bucket_maps)


def _allocate_tables(partitions, depth, width):
    return [[[0 for _ in range(width)] for _ in range(depth)]
            for _ in range(partitions)]


def sketch_term_streams(streams, bucket_maps, width):
    """Estimate weighted item occurrences; does not retain posting identities.

    All partitions use the supplied identical width and row lookup maps.
    No random-hash, signed-update, overflow or Redis compatibility guarantee.
    """
    n, depth = _validated_shape(streams, bucket_maps, width)
    tables = _allocate_tables(len(streams), depth, width)
    total = 0
    for part, stream in enumerate(streams):
        for item, weight in stream:
            total += weight
            for row_index, mapping in enumerate(bucket_maps):
                tables[part][row_index][mapping[item]] += weight
    shards = tuple(tuple(tuple(row) for row in table) for table in tables)
    merged = tuple(tuple(sum(table[r][c] for table in tables)
                         for c in range(width)) for r in range(depth))
    estimates = tuple(min(merged[r][bucket_maps[r][item]]
                          for r in range(depth)) for item in range(n))
    return SketchReport(width, bucket_maps, shards, merged, estimates, total)


def collision_reference(streams, bucket_maps, width):
    """Independent weighted collision-class aggregation, no update-loop helper.

    Valid fixtures only. Expected cells are grouped from exact item masses;
    expected query values use query/item collision equivalence directly.
    """
    n = len(bucket_maps[0])
    masses = tuple(Counter({item: sum(weight for event_item, weight in stream
                                     if event_item == item)
                            for item in range(n)}) for stream in streams)
    shard_tables = tuple(tuple(tuple(sum(mass[item] for item in range(n)
                                          if mapping[item] == bucket)
                                      for bucket in range(width))
                                for mapping in bucket_maps) for mass in masses)
    total_mass = Counter()
    for mass in masses:
        total_mass.update(mass)
    merged = tuple(tuple(sum(total_mass[item] for item in range(n)
                             if mapping[item] == bucket)
                         for bucket in range(width)) for mapping in bucket_maps)
    estimates = tuple(min(sum(total_mass[other] for other in range(n)
                              if mapping[other] == mapping[item])
                          for mapping in bucket_maps) for item in range(n))
    return SketchReport(width, bucket_maps, shard_tables, merged, estimates,
                        sum(total_mass.values()))


def rejects(error, call):
    try:
        call()
    except error:
        return True
    return False


def self_check():
    checks = {}
    maps = ((0, 0, 1), (0, 1, 1))
    streams = (((0, 2), (1, 3)), ((2, 4),))
    before = repr((streams, maps))
    manual = sketch_term_streams(streams, maps, 2)
    checks['weighted_manual_collision_and_literal_tables'] = (
        manual.shard_tables == (((5, 0), (2, 3)), ((0, 4), (0, 4)))
        and manual.merged_table == ((5, 4), (2, 7))
        and manual.estimates == (2, 5, 4) and manual.total_weight == 9)
    absent = sketch_term_streams((((0, 3),),), ((0, 0), (1, 1)), 2)
    checks['never_observed_item_can_have_positive_estimate'] = (
        absent.estimates == (3, 3) and absent.total_weight == 3)
    clean = sketch_term_streams(streams, maps + ((0, 1, 2),), 3)
    checks['one_unpolluted_row_recovers_exact_frequency'] = (
        clean.estimates == (2, 3, 4) and clean.merged_table[-1] == (2, 3, 4))
    exact = (2, 3, 4)
    checks['one_sided_bounds_and_each_row_preserves_total_mass'] = (
        all(actual <= estimate <= manual.total_weight
            for actual, estimate in zip(exact, manual.estimates))
        and all(sum(row) == manual.total_weight for row in manual.merged_table)
        and all(sum(row) == sum(weight for _, weight in stream)
                for stream, table in zip(streams, manual.shard_tables)
                for row in table))
    reordered = sketch_term_streams(tuple(tuple(reversed(s))
                                          for s in reversed(streams)), maps, 2)
    checks['event_and_partition_order_preserve_combined_state'] = (
        reordered.merged_table == manual.merged_table
        and reordered.estimates == manual.estimates
        and reordered.shard_tables == tuple(reversed(manual.shard_tables)))
    flat = tuple(event for stream in streams for event in stream)
    unsplit = sketch_term_streams((flat,), maps, 2)
    shard_minima = tuple(min(table[r][maps[r][1]] for r in range(2))
                        for table in manual.shard_tables)
    checks['cellwise_merge_precedes_minimum_not_sum_of_local_minima'] = (
        unsplit.merged_table == manual.merged_table
        and unsplit.estimates == manual.estimates
        and shard_minima == (3, 0)
        and sum(shard_minima) == 3 != manual.estimates[1] == 5)
    three = (((0, 1),), ((1, 2),), ((2, 3),))
    grouped = sketch_term_streams((three[0] + three[1], three[2], ()), maps, 2)
    separate = sketch_term_streams(three, maps, 2)
    checks['repartition_and_empty_partition_identity'] = (
        grouped.merged_table == separate.merged_table
        and grouped.estimates == separate.estimates
        and grouped.total_weight == separate.total_weight == 6)
    scale_base = (((0, 1), (1, 2)), ((2, 1),))
    doubled = tuple(tuple((item, 2 * weight) for item, weight in stream)
                    for stream in scale_base)
    a = sketch_term_streams(scale_base, maps, 2)
    b = sketch_term_streams(doubled, maps, 2)
    checks['positive_weight_scaling_without_clipping'] = (
        b.merged_table == tuple(tuple(2 * x for x in row) for row in a.merged_table)
        and b.estimates == tuple(2 * x for x in a.estimates)
        and b.total_weight == 2 * a.total_weight)
    row_reports = tuple(sketch_term_streams(streams, rows, 3) for rows in
                        (maps[:1], maps, maps + ((0, 1, 2),)))
    checks['adding_rows_cannot_raise_a_fixed_query_estimate'] = all(
        c <= b <= a for a, b, c in zip(*(report.estimates for report in row_reports)))
    permutation = (2, 0, 1)
    renamed_maps = tuple(tuple(row[permutation.index(new)] for new in range(3))
                         for row in maps)
    renamed_streams = tuple(tuple((permutation[item], weight) for item, weight in stream)
                            for stream in streams)
    renamed = sketch_term_streams(renamed_streams, renamed_maps, 2)
    checks['item_renaming_is_map_column_permutation'] = (
        renamed.merged_table == manual.merged_table
        and renamed.shard_tables == manual.shard_tables
        and renamed.estimates == tuple(manual.estimates[permutation.index(i)]
                                       for i in range(3)))
    empty = sketch_term_streams(((), (), (), ()), ((0,) * 6,), 1)
    single = sketch_term_streams((((0, 2), (0, 1)),), ((3,), (1,), (0,)), 4)
    cap_streams = tuple(tuple((i % 6, 4) for i in range(8)) for _ in range(4))
    cap_maps = (tuple(i % 4 for i in range(6)), tuple((i + 1) % 4 for i in range(6)),
                tuple((3 - i) % 4 for i in range(6)))
    cap = sketch_term_streams(cap_streams, cap_maps, 4)
    checks['empty_width_one_single_item_and_all_declared_caps'] = (
        empty.estimates == (0,) * 6 and empty.total_weight == 0
        and empty.merged_table == ((0,),)
        and single.estimates == (3,) and single.total_weight == 3
        and cap.total_weight == 128 and len(cap.shard_tables) == 4
        and all(len(table) == 3 and all(len(row) == 4 for row in table)
                for table in cap.shard_tables)
        and all(sum(row) == 128 for row in cap.merged_table))
    class IntChild(int):
        pass
    class TupleChild(tuple):
        pass
    lazy_events = []
    class NeverIterate:
        def __iter__(self):
            lazy_events.append('consumed')
            raise AssertionError('lazy coercion forbidden')
    good_maps = ((0, 1),)
    good_streams = (((0, 1),),)
    bad_types = [
        (good_streams, good_maps, True), (good_streams, good_maps, 2.0),
        (good_streams, good_maps, IntChild(2)), (good_streams, [(0, 1)], 2),
        (good_streams, ([0, 1],), 2), (good_streams, TupleChild(good_maps), 2),
        (good_streams, (TupleChild((0, 1)),), 2),
        (good_streams, ((False, 1),), 2), (good_streams, ((0.0, 1),), 2),
        (good_streams, ((IntChild(0), 1),), 2),
        ([((0, 1),)], good_maps, 2), (TupleChild(good_streams), good_maps, 2),
        (([(0, 1)],), good_maps, 2), ((TupleChild(((0, 1),)),), good_maps, 2),
        ((([0, 1],),), good_maps, 2),
        (((TupleChild((0, 1)),),), good_maps, 2),
        ((((True, 1),),), good_maps, 2), ((((0.0, 1),),), good_maps, 2),
        ((((IntChild(0), 1),),), good_maps, 2),
        ((((0, True),),), good_maps, 2), ((((0, 1.0),),), good_maps, 2),
        ((((0, IntChild(1)),),), good_maps, 2), (NeverIterate(), good_maps, 2)]
    bad_values = [
        (good_streams, good_maps, 0), (good_streams, good_maps, 5),
        (good_streams, (), 2), (good_streams, good_maps * 4, 2),
        (((),), ((),), 2), (((),), ((0,) * 7,), 2),
        (((),), ((0, 1), (0,)), 2),
        (good_streams, ((-1, 1),), 2), (good_streams, ((0, 2),), 2),
        ((), good_maps, 2), (good_streams * 5, good_maps, 2),
        ((((0, 1),) * 9,), good_maps, 2),
        ((((0,),),), good_maps, 2), ((((0, 1, 2),),), good_maps, 2),
        ((((-1, 1),),), good_maps, 2), ((((2, 1),),), good_maps, 2),
        ((((0, 0),),), good_maps, 2), ((((0, 5),),), good_maps, 2),
        ((((0, -1),),), good_maps, 2)]
    allocation_events = []
    def allocation_trap(*args):
        allocation_events.append(args)
        raise AssertionError('invalid request reached counter allocation')
    real_allocate = globals()['_allocate_tables']
    globals()['_allocate_tables'] = allocation_trap
    try:
        admission_ok = all(rejects(TypeError, lambda q=q: sketch_term_streams(*q))
                           for q in bad_types)
        admission_ok &= all(rejects(ValueError, lambda q=q: sketch_term_streams(*q))
                            for q in bad_values)
    finally:
        globals()['_allocate_tables'] = real_allocate
    checks['whole_strict_admission_before_counter_allocation'] = bool(
        admission_ok and allocation_events == [] and lazy_events == [])
    family_ok = True
    profiles = 0
    compared_item_estimates = 0
    row_options = tuple(product(range(2), repeat=3))
    stream_profiles = 0
    for mapping_pair in product(row_options, repeat=2):
        per_map_profiles = 0
        for length in range(5):
            for items in product(range(3), repeat=length):
                events = tuple((item, item + 1) for item in items)
                partitions = (events[::2], events[1::2])
                actual = sketch_term_streams(partitions, mapping_pair, 2)
                expected = collision_reference(partitions, mapping_pair, 2)
                family_ok &= actual == expected
                profiles += 1
                per_map_profiles += 1
                compared_item_estimates += 3
        stream_profiles = per_map_profiles
    checks['ONE_exhaustive_map_stream_family_collision_class_reference'] = bool(
        family_ok and profiles == len(row_options) ** 2 * stream_profiles
        and compared_item_estimates == 3 * profiles)
    fresh = sketch_term_streams(streams, maps, 2)
    checks['fresh_nested_immutable_reports_and_input_preservation'] = (
        fresh == manual and fresh is not manual
        and fresh.merged_table is not manual.merged_table
        and repr((streams, maps)) == before
        and rejects(FrozenInstanceError, lambda: setattr(fresh, 'total_weight', 0))
        and rejects(TypeError, lambda: operator.setitem(fresh.estimates, 0, 0))
        and rejects(TypeError, lambda: operator.setitem(fresh.merged_table[0], 0, 0))
        and rejects(TypeError, lambda: operator.setitem(fresh.shard_tables[0][0], 0, 0)))
    assert len(checks) == 14 and all(type(value) is bool for value in checks.values())
    assert all(checks.values()), checks
    return {
        'runtime': {'python': platform.python_version(),
                    'implementation': platform.python_implementation(),
                    'dependencies': 'standard library only', 'Redis_executed': False},
        'manual': {'streams': streams, 'bucket_maps': maps, 'report': asdict(manual),
                   'exact_reference_counts': exact},
        'merge_minima_counterexample': {'item_id': 1, 'shard_minima': shard_minima,
                                        'sum_of_shard_minima': sum(shard_minima),
                                        'minimum_after_cellwise_merge': manual.estimates[1]},
        'never_observed': {'unseen_item_id': 1, 'exact_count': 0,
                           'estimated_count': absent.estimates[1]},
        'independent_family': {'map_profiles': len(row_options) ** 2,
                               'event_profiles_per_map': stream_profiles,
                               'compared_profiles': profiles,
                               'compared_item_estimates': compared_item_estimates,
                               'counted_as_meaningful_groups': 1,
                               'oracle': 'Exact per-item mass and collision-class sums, no incremental sketch helper.'},
        'admission_and_caps': {'type_profiles': len(bad_types),
                                'value_or_size_profiles': len(bad_values),
                                'invalid_counter_allocations': len(allocation_events),
                                'lazy_iterable_consumptions': len(lazy_events),
                                'maximum_total_weight': cap.total_weight},
        'meaningful_named_groups': len(checks), 'checks': checks,
        'limits': ['Supplied deterministic maps: algebraic overcount bound only, no epsilon/delta claim.',
                   'Strict positive integer updates; no deletions, saturation or fixed-width overflow model.',
                   'Explicit map metadata and finite fixtures are not a measured memory/speed benefit.',
                   'No postings, document frequency, cardinality, search relevance, Redis execution or compatibility.']}


if __name__ == '__main__':
    sys.stdout.reconfigure(encoding='utf-8', newline='\n')
    print(json.dumps(self_check(), ensure_ascii=True, indent=2))

گزارشِ اجرا، نسخهٔ واقعیِ پایتون و چهارده گروهِ نام‌دار را همراهِ خروجیِ نمونه نگه می‌دارد. یک گروه، خانوادهٔ کاملِ نگاشت‌های دوخانه‌ای و جریان‌های کوچک را با مرجعِ کلاسِ برخورد مقایسه می‌کند؛ هزاران ورودی، هزاران گروهِ مستقل شمرده نمی‌شوند. گروه‌های جدا، مرزِ تهی، سقف‌ها، تغییرِ ترتیب، تغییرِ نامِ شناسه، مقیاسِ وزن، ردِ ورودی پیش از تخصیص و تغییرناپذیریِ گزارش را می‌سنجند. این بررسی‌ها آزمایشِ زمان یا حافظه نیستند.

{
  "runtime": {
    "python": "3.14.5",
    "implementation": "CPython",
    "dependencies": "standard library only",
    "Redis_executed": false
  },
  "manual": {
    "streams": [
      [
        [
          0,
          2
        ],
        [
          1,
          3
        ]
      ],
      [
        [
          2,
          4
        ]
      ]
    ],
    "bucket_maps": [
      [
        0,
        0,
        1
      ],
      [
        0,
        1,
        1
      ]
    ],
    "report": {
      "width": 2,
      "bucket_maps": [
        [
          0,
          0,
          1
        ],
        [
          0,
          1,
          1
        ]
      ],
      "shard_tables": [
        [
          [
            5,
            0
          ],
          [
            2,
            3
          ]
        ],
        [
          [
            0,
            4
          ],
          [
            0,
            4
          ]
        ]
      ],
      "merged_table": [
        [
          5,
          4
        ],
        [
          2,
          7
        ]
      ],
      "estimates": [
        2,
        5,
        4
      ],
      "total_weight": 9
    },
    "exact_reference_counts": [
      2,
      3,
      4
    ]
  },
  "merge_minima_counterexample": {
    "item_id": 1,
    "shard_minima": [
      3,
      0
    ],
    "sum_of_shard_minima": 3,
    "minimum_after_cellwise_merge": 5
  },
  "never_observed": {
    "unseen_item_id": 1,
    "exact_count": 0,
    "estimated_count": 3
  },
  "independent_family": {
    "map_profiles": 64,
    "event_profiles_per_map": 121,
    "compared_profiles": 7744,
    "compared_item_estimates": 23232,
    "counted_as_meaningful_groups": 1,
    "oracle": "Exact per-item mass and collision-class sums, no incremental sketch helper."
  },
  "admission_and_caps": {
    "type_profiles": 23,
    "value_or_size_profiles": 19,
    "invalid_counter_allocations": 0,
    "lazy_iterable_consumptions": 0,
    "maximum_total_weight": 128
  },
  "meaningful_named_groups": 14,
  "checks": {
    "weighted_manual_collision_and_literal_tables": true,
    "never_observed_item_can_have_positive_estimate": true,
    "one_unpolluted_row_recovers_exact_frequency": true,
    "one_sided_bounds_and_each_row_preserves_total_mass": true,
    "event_and_partition_order_preserve_combined_state": true,
    "cellwise_merge_precedes_minimum_not_sum_of_local_minima": true,
    "repartition_and_empty_partition_identity": true,
    "positive_weight_scaling_without_clipping": true,
    "adding_rows_cannot_raise_a_fixed_query_estimate": true,
    "item_renaming_is_map_column_permutation": true,
    "empty_width_one_single_item_and_all_declared_caps": true,
    "whole_strict_admission_before_counter_allocation": true,
    "ONE_exhaustive_map_stream_family_collision_class_reference": true,
    "fresh_nested_immutable_reports_and_input_preservation": true
  },
  "limits": [
    "Supplied deterministic maps: algebraic overcount bound only, no epsilon/delta claim.",
    "Strict positive integer updates; no deletions, saturation or fixed-width overflow model.",
    "Explicit map metadata and finite fixtures are not a measured memory/speed benefit.",
    "No postings, document frequency, cardinality, search relevance, Redis execution or compatibility."
  ]
}

۵. چهار پرسش و مرزِ تقریب

کیتِ آموزشیِ محدود در کنار کابلِ جدا و دفترِ بسته
تصویر مفهومی: کیتِ آموزشیِ محدود در کنار کابلِ جدا و دفترِ بسته؛ بدون مقیاس عددی و مستقل از نتایج اجرای کد.

پرسشِ اول: آیا پاسخِ مثبت ثابت می‌کند واژه آمده است؟ خیر؛ شناسهٔ هرگزندیده هم ممکن است در تمامِ ردیف‌ها با شناسه‌های دیگر برخورد کند. اگر تصمیم به شاهدِ حضور نیاز دارد، دادهٔ دقیقِ جدا لازم است. در مقابل، پاسخِ صفر در مدلِ افزایشیِ سالم نشان می‌دهد فراوانیِ واقعی صفر است؛ این نتیجه به ثابت ماندنِ طرح و نبودِ دست‌کاری وابسته است، نه به اصالت یا اعتبارِ رویدادها.

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

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

پرسشِ چهارم: آیا این مثال صرفه‌جوییِ حافظه یا دقتِ سرویس را ثابت می‌کند؟ خیر؛ نگاشتِ صریحِ تمامِ شناسه‌ها و جدول‌های بخش‌ها برای آموزش نگهداری می‌شوند و خودشان هزینه دارند. خروجیِ متناهی، توزیعِ درخواست‌های آینده یا کاراییِ جست‌وجو را تعیین نمی‌کند. خلاصه فقط فراوانیِ وزنی را تقریب می‌زند؛ هویتِ سند، معنای واژه، تازگی، مجوز و سیاستِ رتبه‌بندی همچنان به طراحیِ جدا نیاز دارند.

منابع و مطالعهٔ بیشتر

بررسی منابع: ۳۰ مهر ۱۴۰۵. تحلیل‌ها و پیشنهادهای اجرایی، جمع‌بندی نویسنده‌اند.