Skip to content

Registry validation still scales poorly after #52; progress stops after 60 seconds #54

Open

Description

@anthonyprintup

Summary

Follow-up to #50 / #52: batched registry validation still performs a large cross-product of filesystem identity checks as retained claims accumulate. A long validation holds the shared registry lock, and its progress reporter stops producing periodic messages after about one minute.

The earlier optimization is present: this report does not claim that the registry is still scanned separately for each current plan. The standalone POC below records one registry validation per measured reconciliation. The remaining cost is repeated path projection and physical containment/alias work inside that validation.

Tested public revision: a37bde7156f444a22f7ab9d42392c91adb54ad30.
Coordinator source SHA-256: 2ff54b69242d46eb8e35a52d30b32bc9afd815c00b6c0abeb8765d6fe7ddbb85.
Environment: Windows, CPython 3.12.9. Consumer names, paths, host/device identifiers and raw consumer records are deliberately omitted.

Observations

An anonymized consumer workload completed successfully with:

  • 11 current plans and 2,172 retained registry entries checked.
  • 751.875 seconds in validation, 0.328 seconds waiting for locks, and 1.969 seconds in reconciliation (754.172 seconds total).
  • Progress advancing from 11 claims at five seconds to 154 claims at sixty seconds, followed by no further periodic messages until completion at 2,172 claims.

This was useful work rather than a deadlock, but roughly twelve and a half minutes were spent validating ownership before subsequent build work.

A separate read-only sample using the exact coordinator and six representative retained claims against eleven current plans performed 24,228 stat calls, 1,972 lstat calls and 1,392 final-path resolutions. Those metadata calls accounted for approximately 88% of that instrumented sample's elapsed time. Reading all claim JSON records in a separate registry inventory took about 0.22 seconds; the evidence points to repeated identity/path work rather than bulk JSON I/O.

The registry inventory spanned hundreds of build identities and included test-created claims. This is evidence that accumulated unrelated claims amplify the cost; it is not proof of an ownership leak or justification for deleting retained state. Review lifecycle/test isolation separately.

Standalone synthetic reproduction

Only Python 3.12+ and this repository's coordinator are needed. No CMake configure, schema compiler, C++ compiler, network access or consuming project is involved.

Save the script at the end of this issue as registry_validation_poc.py in a disposable checkout of the tested revision, then run:

python -B registry_validation_poc.py --claims 0 8 16 --plans 1 11 --work ./registry-poc-run

The workspace must not already exist. Every sample uses a separate synthetic registry with one target/output per plan. The script never opens the user's default/shared registry or edits the coordinator. It retains its private fixtures and writes an anonymized results.json. Publish only that results file, not the fixture directory: synthetic claim records necessarily contain the executing machine's temporary paths.

Fixture setup is timed separately. Seeding uses the coordinator's real initialization/reconciliation helpers under the isolated registry/generation/publication locks, avoiding an expensive all-pairs setup pass. The measured call is the normal reconcile_set((), current_plans); profiling/counter wrappers delegate its checks, locking and filesystem operations unchanged. No generated payload is published and no validation is skipped in the measured call.

For a larger workload, explicitly opt into --claims 2048 --plans 11 --repeat 1; expect minutes on affected systems. The small matrix already demonstrates the operation-count growth. Timings below are single-run, instrumented measurements and vary with path depth, filesystem/cache state and concurrent activity.

Retained claims Current plans Validation seconds Path projections Windows stat calls
0 1 0.014 12 381
0 11 0.128 132 4191
8 1 0.226 229 4907
8 11 1.389 1069 32737
16 1 0.537 445 9411
16 11 2.731 2005 61161

All six samples completed successfully. For example, sixteen retained claims and eleven current plans produced 61,161 stat calls during validation alone.

The same script includes a short progress demonstration. It changes only the reporting interval from five seconds to 0.01 seconds in its own process, then advances forty synthetic claims. Observed: twelve periodic reports, a suppression message at the last periodic report, further claim advancement, and a final completion message. The production interval/report cap imply a nominal sixty-second cutoff; the accelerated demonstration is not a sixty-second wall-time measurement.

Relevant implementation

Requested follow-up / acceptance

  • Reduce repeated filesystem identity work in registry validation. Evaluate an ownership/index design and explicitly bounded reuse of observations; define the consistency/revalidation boundary before implementing caching.
  • Preserve physical alias, junction/symlink, path-replacement/TOCTOU, overlap, ownership, concurrent-writer and crash-recovery protections. Do not address the cost by clearing claims, splitting the shared lock namespace, skipping foreign records, disabling checks or merely increasing timeouts.
  • Add representative scaling coverage for thousands of retained claims and multiple current plans. Keep setup and validation separate and use operation counts as well as descriptive timings. The existing benchmark defaults to small workloads and currently caps retained claims at 500.
  • Audit test registry isolation and retained-claim lifecycle. Any cleanup needs ownership-aware semantics; old/test-looking records are not automatically disposable.
  • Continue bounded-frequency progress updates throughout long operations, possibly backing off the interval. Retain phase, checked/total claims and lock/validation timing so continued work is visible after the first minute.
  • Demonstrate lower repeated work and shorter shared-lock occupancy while retaining the relevant adversarial filesystem/concurrency tests.
Standalone registry_validation_poc.py (standard library only)
"""Standalone output-registry scaling/progress POC; Python 3.12+, stdlib only.

Run from a Protocyte checkout. All state lives in a NEW synthetic workspace;
the default/shared registry and source checkout are never modified.
Fixtures are retained locally. Publish only this script and results.json,
not the synthetic claim files (which necessarily contain local paths).
"""
from __future__ import annotations

import argparse
import contextlib
import cProfile
import hashlib
import importlib.util
import io
import json
import os
import platform
import pstats
import re
import sys
import tempfile
import time
from pathlib import Path


def load(path):
    spec = importlib.util.spec_from_file_location("coordinator_poc", path)
    module = importlib.util.module_from_spec(spec)
    sys.modules[spec.name] = module
    spec.loader.exec_module(module)
    return module


def plan(module, work, name):
    directory = work / name
    build = directory / "build"
    build.mkdir(parents=True)
    root = directory / "generated"
    target = hashlib.sha256(name.encode()).hexdigest()
    staging = directory / (".protocyte-generation-staging-" + target)
    encoded = lambda value: os.fspath(value).encode("utf-8").hex()
    path = directory / "outputs.plan"
    path.write_text(
        "\n".join([
            module.PLAN_HEADER,
            "root-hex=" + encoded(root),
            "build-root-hex=" + encoded(build),
            "target=" + target + "|" + encoded(staging),
            "output=" + target + "|" + encoded("sample.protocyte.hpp"),
        ]) + "\n",
        encoding="ascii",
    )
    return module.Plan.read(path)


def sample(module, work, retained_count, current_count):
    setup_start = time.perf_counter()
    retained = [
        plan(module, work, "retained-%04d" % i) for i in range(retained_count)
    ]
    current = [
        plan(module, work, "current-%04d" % i) for i in range(current_count)
    ]
    engine = module.OutputCoordinator(work / "isolated-registry")

    # Fixture seeding only: avoid quadratic conflict comparisons during setup.
    # Use real initialization/reconciliation helpers under PRIVATE locks.
    # No method is replaced during seeding; all roots/targets are disjoint.
    module._durable_mkdir(engine.lock_root)
    with module.FileLock(engine.lock_root / "registry.lock"):
        for item in retained:
            with (
                module.FileLock(engine._generation_lock(item.root)),
                module.FileLock(engine._publication_lock(item.root)),
            ):
                state = engine._state_directory(item.root)
                engine._initialize_claim_locked(state, item)
                engine._reconcile_locked(state, item)
    setup_seconds = time.perf_counter() - setup_start

    active = False
    counts = {}
    originals = {}
    profile = cProfile.Profile()
    validation_wall = validation_cpu = 0.0
    original_validate = engine._validate_registry

    def validate(*args, **kwargs):
        nonlocal active, validation_wall, validation_cpu
        counts["registry_validations"] = counts.get("registry_validations", 0) + 1
        active = True
        wall, cpu = time.perf_counter(), time.process_time()
        profile.enable()
        try:
            return original_validate(*args, **kwargs)
        finally:
            profile.disable()
            validation_wall += time.perf_counter() - wall
            validation_cpu += time.process_time() - cpu
            active = False

    names = (
        "project_path", "_paths_overlap", "_path_key",
        "_physical_location_key", "_same_physical_path",
    )
    for name in names:
        original = getattr(module, name)
        originals[name] = original

        def counted(*args, _name=name, _original=original, **kwargs):
            if active:
                counts[_name] = counts.get(_name, 0) + 1
            return _original(*args, **kwargs)

        setattr(module, name, counted)
    engine._validate_registry = validate
    wall, cpu = time.perf_counter(), time.process_time()
    try:
        # This is the measured production operation, with every check,
        # filesystem call, and lock delegated unchanged.
        tokens = engine.reconcile_set((), current)
    finally:
        reconcile_wall = time.perf_counter() - wall
        reconcile_cpu = time.process_time() - cpu
        engine._validate_registry = original_validate
        for name, original in originals.items():
            setattr(module, name, original)
    assert len(tokens) == current_count and all(tokens)

    filesystem = {}
    for (_, _, name), (_, calls, own, _, _) in pstats.Stats(profile).stats.items():
        for operation in ("nt.stat", "nt.lstat", "nt._getfinalpathname"):
            if name == "<built-in method %s>" % operation:
                filesystem[operation] = {
                    "calls": calls,
                    "own_seconds": round(own, 6),
                }
    return {
        "retained_claims": retained_count,
        "current_plans": current_count,
        "setup_seconds": round(setup_seconds, 6),
        "validation_wall_seconds": round(validation_wall, 6),
        "validation_cpu_seconds": round(validation_cpu, 6),
        "reconcile_wall_seconds": round(reconcile_wall, 6),
        "reconcile_cpu_seconds": round(reconcile_cpu, 6),
        "validation_operation_counts": counts,
        "validation_filesystem_calls": filesystem,
        "completed_plans": len(tokens),
    }


def progress_demo(module):
    """Demonstrate the cutoff quickly; only the reporting interval is scaled."""
    original_interval = module._ReconcileProgress.INTERVAL_SECONDS
    max_reports = module._ReconcileProgress.MAX_REPORTS
    stream = io.StringIO()
    try:
        module._ReconcileProgress.INTERVAL_SECONDS = 0.01
        with contextlib.redirect_stderr(stream):
            with module._ReconcileProgress(1, 0) as progress:
                progress.phase("validating registry", "validation")
                progress.registry(states=100)
                for _ in range(40):
                    progress.registry(claim=True)
                    time.sleep(0.01)
    finally:
        module._ReconcileProgress.INTERVAL_SECONDS = original_interval
    lines = stream.getvalue().splitlines()
    periodic = [line for line in lines if ": complete;" not in line]
    last = periodic[-1] if periodic else ""
    match = re.search(r"claims_checked=(\d+)", last)
    return {
        "production_interval_seconds": original_interval,
        "production_max_periodic_reports": max_reports,
        "nominal_production_cutoff_seconds": original_interval * max_reports,
        "demo_interval_seconds": 0.01,
        "periodic_reports": len(periodic),
        "claims_at_last_periodic_report": int(match[1]) if match else None,
        "claims_at_completion": progress._claims,
        "suppression_message_seen": "further progress suppressed" in last,
        "completion_message_seen": any(": complete;" in line for line in lines),
    }


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--coordinator", type=Path,
        default=Path("cmake/ProtocyteOutputCoordinator.py"),
    )
    parser.add_argument("--claims", type=int, nargs="+", default=[0, 8, 16])
    parser.add_argument("--plans", type=int, nargs="+", default=[1, 11])
    parser.add_argument("--repeat", type=int, default=1)
    parser.add_argument("--work", type=Path)
    args = parser.parse_args()
    if (any(not 0 <= n <= 4096 for n in args.claims)
            or any(not 1 <= n <= 32 for n in args.plans)
            or not 1 <= args.repeat <= 10):
        parser.error("expected 0..4096 claims, 1..32 plans, 1..10 repetitions")
    source = args.coordinator.resolve(strict=True)
    module = load(source)
    if args.work:
        root = args.work.absolute()
        root.mkdir(parents=True, exist_ok=False)
    else:
        root = Path(tempfile.mkdtemp(prefix="protocyte-registry-poc-"))
    root = root.resolve(strict=True)
    result = {
        "os": platform.system(),
        "python": platform.python_version(),
        "coordinator_sha256": hashlib.sha256(source.read_bytes()).hexdigest(),
        "timings_include_instrumentation": True,
        "samples": [],
    }
    for repetition in range(args.repeat):
        for claims in args.claims:
            for plans in args.plans:
                work = root / ("r%d-c%d-p%d" % (repetition, claims, plans))
                row = {"repetition": repetition, **sample(module, work, claims, plans)}
                result["samples"].append(row)
                print(json.dumps(row), flush=True)
    result["progress_demo"] = progress_demo(module)
    (root / "results.json").write_text(
        json.dumps(result, indent=2) + "\n", encoding="utf-8"
    )
    print(json.dumps(result["progress_demo"]), flush=True)


if __name__ == "__main__":
    main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

No labels
No labels

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions