蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行 ACID 回滚、CAP 分区权衡、社交图/百科查询及六大 NoSQL 范式离线验证

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-nosql.py
explore-nosql.py208 行
"""Offline NoSQL ACID/CAP/BASE & six-model taxonomy verifier (Ch02 nosql)."""
import copy
import json
from collections import deque
import xml.etree.ElementTree as ET

VERSION = "CPython 3.12.14 offline MongoDB document/query verifier (mongod absent)"


def case_acid_bank_transfer_atomicity_and_consistency():
    committed = {"A": 600, "B": 400}

    def transfer(accounts, src, dst, amount, inject_error=False):
        working = copy.deepcopy(accounts)
        if working[src] < amount:
            return accounts, False, "insufficient_funds"
        working[src] -= amount
        if inject_error:
            # Rollback: committed state untouched; isolation hides uncommitted debit
            return accounts, False, "rolled_back"
        working[dst] += amount
        assert working["A"] + working["B"] == accounts["A"] + accounts["B"]
        return working, True, "committed"

    after_fail, ok1, msg1 = transfer(committed, "A", "B", 100, inject_error=True)
    after_ok, ok2, msg2 = transfer(after_fail, "A", "B", 100, inject_error=False)
    actual = {
        "failed_tx": {"ok": ok1, "status": msg1, "balances": after_fail},
        "succeeded_tx": {"ok": ok2, "status": msg2, "balances": after_ok},
        "total_invariant_preserved": (after_fail["A"] + after_fail["B"] == 1000)
        and (after_ok["A"] + after_ok["B"] == 1000),
    }
    expected = {
        "failed_tx": {"ok": False, "status": "rolled_back", "balances": {"A": 600, "B": 400}},
        "succeeded_tx": {"ok": True, "status": "committed", "balances": {"A": 500, "B": 500}},
        "total_invariant_preserved": True,
    }
    return {
        "name": "acid_bank_transfer_atomicity_and_consistency",
        "summary": "验证 ACID 转账事务在异常时回滚保证原子性与总额守恒,提交后生效。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_cap_theorem_tradeoff_simulation():
    # Network partition splits cluster into majority (2 nodes) and minority (1 node)
    def write_cp(partition_side: str, value: str):
        if partition_side != "majority":
            return {"accepted": False, "reason": "no_quorum_preserve_consistency"}
        return {"accepted": True, "value": value}

    def write_ap(node_store: dict, key: str, value: str, ts: int):
        node_store[key] = (value, ts)
        return {"accepted": True, "value": value}

    cp_minority = write_cp("minority", "v2")
    cp_majority = write_cp("majority", "v2")

    ap_node1 = {"profile": ("v1", 1)}
    ap_node2 = {"profile": ("v1", 1)}
    write_ap(ap_node1, "profile", "v2_a", 2)
    write_ap(ap_node2, "profile", "v2_b", 3)
    diverged_during_partition = ap_node1["profile"][0] != ap_node2["profile"][0]
    # Heal partition via Last-Write-Wins (eventual consistency)
    winner = max([ap_node1["profile"], ap_node2["profile"]], key=lambda x: x[1])
    ap_node1["profile"] = ap_node2["profile"] = winner
    converged = ap_node1["profile"] == ap_node2["profile"] == ("v2_b", 3)

    actual = {
        "cp_rejects_minority": not cp_minority["accepted"],
        "cp_accepts_majority": cp_majority["accepted"],
        "ap_diverged_during_partition": diverged_during_partition,
        "ap_converged_after_heal": converged,
    }
    expected = {
        "cp_rejects_minority": True,
        "cp_accepts_majority": True,
        "ap_diverged_during_partition": True,
        "ap_converged_after_heal": True,
    }
    return {
        "name": "cap_theorem_tradeoff_simulation",
        "summary": "模拟网络分区下 CP 拒绝少数派写入保一致、AP 两侧接受写入并在分区恢复后最终一致。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_social_graph_and_wiki_document_tasks():
    # Task 1: Social graph multi-hop friends traversal
    edges = [("u1", "u2"), ("u2", "u3"), ("u3", "u4"), ("u1", "u5")]
    adj = {}
    for a, b in edges:
        adj.setdefault(a, []).append(b)
        adj.setdefault(b, []).append(a)
    visited = {"u1"}
    q = deque([("u1", 0)])
    reachable = {}
    while q:
        u, d = q.popleft()
        if d > 0:
            reachable[u] = d
        for nxt in adj.get(u, []):
            if nxt not in visited:
                visited.add(nxt)
                q.append((nxt, d + 1))

    # Task 2: Wikipedia semi-structured document filtering
    wiki_docs = [
        {"title": "1936 Summer Olympics Athletics", "tags": ["athletics", "Summer Olympic"], "year": 1936},
        {"title": "1948 Summer Olympics Track", "tags": ["athletics", "Summer Olympic"], "year": 1948},
        {"title": "1964 Summer Olympics Athletics", "tags": ["athletics", "Summer Olympic"], "year": 1964},
        {"title": "1924 Winter Olympics Skiing", "tags": ["skiing", "Winter Olympic"], "year": 1924},
    ]
    matched_wiki = [
        d["title"]
        for d in wiki_docs
        if "athletics" in d["tags"] and "Summer Olympic" in d["tags"] and d["year"] < 1950
    ]

    actual = {
        "social_hop_distances": reachable,
        "wiki_pre1950_athletics": matched_wiki,
    }
    expected = {
        "social_hop_distances": {"u2": 1, "u5": 1, "u3": 2, "u4": 3},
        "wiki_pre1950_athletics": ["1936 Summer Olympics Athletics", "1948 Summer Olympics Track"],
    }
    return {
        "name": "social_graph_and_wiki_document_tasks",
        "summary": "验证社交关系多跳好友遍历与半结构化百科文档检索两个典型 NoSQL 场景。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_acid_vs_base_matrix_check():
    acid = ["Atomicity", "Consistency", "Isolation", "Durability"]
    base = ["Basically Available", "Soft state", "Eventual consistency"]
    actual = {"acid_count": len(acid), "base_count": len(base), "cap_max_simultaneous": 2}
    expected = {"acid_count": 4, "base_count": 3, "cap_max_simultaneous": 2}
    return {
        "name": "acid_vs_base_matrix_check",
        "summary": "核对 ACID 四特性、BASE 三原则与 CAP 三选二权衡基线。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_nosql_six_model_taxonomy():
    # Column-family projection: read only one column across rows
    col_store = {"col_clicks": [120, 340, 210], "col_title": ["A", "B", "C"]}
    # Document store indexed field filter
    doc_store = [{"name": "MongoDB", "type": "document"}, {"name": "CouchDB", "type": "document"}]
    # Key-value O(1) lookup
    kv_store = {"session:42": "active"}
    # Graph adjacency
    graph_store = {"Alice": ["Bob", "Carol"]}
    # Object representation
    obj_record = {"class": "User", "fields": {"id": 1, "role": "member"}}
    # XML XPath query
    root = ET.fromstring("<catalog><db name='BaseX'/><db name='BerkeleyDBXML'/></catalog>")
    xml_names = [el.attrib["name"] for el in root.findall("./db")]

    actual = {
        "column_sum": sum(col_store["col_clicks"]),
        "document_count": len(doc_store),
        "kv_hit": kv_store["session:42"],
        "graph_degree": len(graph_store["Alice"]),
        "object_class": obj_record["class"],
        "xml_xpath_matches": xml_names,
    }
    expected = {
        "column_sum": 670,
        "document_count": 2,
        "kv_hit": "active",
        "graph_degree": 2,
        "object_class": "User",
        "xml_xpath_matches": ["BaseX", "BerkeleyDBXML"],
    }
    return {
        "name": "nosql_six_model_taxonomy",
        "summary": "用 Python 数据模型逐一验证列存储、文档、键值、图、对象与 XML 六大 NoSQL 存储范式。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_acid_bank_transfer_atomicity_and_consistency(),
        case_cap_theorem_tradeoff_simulation(),
        case_social_graph_and_wiki_document_tasks(),
        case_acid_vs_base_matrix_check(),
        case_nosql_six_model_taxonomy(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/mongodb-nosql-lab/explore-nosql.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-nosql.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:MongoDB

课程关联工程包(登记关联49章) · 含当前章节或实例 · mbskycom202612a1732.zip

下载课程关联工程包:MongoDB

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1756.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习