chore: import upstream snapshot with attribution
Integ / changes (push) Has been skipped
Pre-commit / pre-commit (push) Failing after 1s
CLI exit codes / changes (push) Has been skipped
Test (Install) / changes (push) Has been skipped
Test (Python) / changes (push) Has been skipped
Test (TypeScript) / changes (push) Has been skipped
CLI exit codes / cli-gate (push) Has been cancelled
Test (Install) / test-install-gate (push) Has been cancelled
Integ / integ-gate (push) Has been cancelled
Test (Python) / test-python-gate (push) Has been cancelled
Test (TypeScript) / test-typescript-gate (push) Has been cancelled
Test (Install) / python-minimal (3.12) (push) Has been cancelled
Test (Install) / python-minimal (3.11) (push) Has been cancelled
Test (Install) / python-extra (agno, mirage.agents.agno) (push) Has been cancelled
Test (Install) / python-extra (chroma, mirage.resource.chroma) (push) Has been cancelled
Test (Install) / python-extra (pdf, mirage.core.filetype.pdf) (push) Has been cancelled
Integ / integ (push) Has been cancelled
Integ / integ-database (push) Has been cancelled
Integ / integ-database-ts (push) Has been cancelled
Integ / integ-data (push) Has been cancelled
Integ / integ-ssh (push) Has been cancelled
Integ / integ-ssh-ts (push) Has been cancelled
Test (Python) / audit (push) Has been cancelled
Test (TypeScript) / test (push) Has been cancelled
Test (TypeScript) / python-fs-shim (push) Has been cancelled
CLI exit codes / Python CLI (push) Has been cancelled
CLI exit codes / TypeScript CLI (push) Has been cancelled
CLI exit codes / Cross-language snapshot interop (push) Has been cancelled
Test (Python) / test (push) Has been cancelled
Test (Python) / import-isolation (deepagents, openai, mirage.agents.openai_agents) (push) Has been cancelled
Test (Python) / import-isolation (deepagents, pydantic-ai, mirage.agents.pydantic_ai) (push) Has been cancelled
Integ / integ-ts (push) Has been cancelled
Integ / integ-fuse (push) Has been cancelled
Test (Install) / python-extra (databricks, mirage.resource.databricks_volume) (push) Has been cancelled
Test (Install) / python-extra (deepagents, mirage.agents.langchain) (push) Has been cancelled
Test (Install) / python-extra (email, mirage.resource.email) (push) Has been cancelled
Test (Install) / python-extra (fuse, mirage.fuse.mount) (push) Has been cancelled
Test (Install) / python-extra (hdf5, mirage.core.filetype.hdf5) (push) Has been cancelled
Test (Install) / python-extra (hf, mirage.resource.hf_buckets) (push) Has been cancelled
Test (Install) / python-extra (lancedb, mirage.resource.lancedb) (push) Has been cancelled
Test (Install) / python-extra (langfuse, mirage.resource.langfuse) (push) Has been cancelled
Test (Install) / python-extra (mongodb, mirage.resource.mongodb) (push) Has been cancelled
Test (Install) / python-extra (nextcloud, mirage.resource.nextcloud) (push) Has been cancelled
Test (Install) / python-extra (openai, mirage.agents.openai_agents) (push) Has been cancelled
Test (Install) / python-extra (openhands, mirage.agents.openhands, 3.12) (push) Has been cancelled
Test (Install) / python-extra (parquet, mirage.core.filetype.parquet) (push) Has been cancelled
Test (Install) / python-extra (postgres, mirage.resource.postgres) (push) Has been cancelled
Test (Install) / python-extra (pydantic-ai, mirage.agents.pydantic_ai) (push) Has been cancelled
Test (Install) / python-extra (qdrant, mirage.resource.qdrant) (push) Has been cancelled
Test (Install) / python-extra (redis, mirage.resource.redis) (push) Has been cancelled
Test (Install) / python-extra (s3, mirage.resource.s3) (push) Has been cancelled
Test (Install) / python-extra (ssh, mirage.resource.ssh) (push) Has been cancelled
Test (Install) / ts-minimal (push) Has been cancelled

This commit is contained in:
wehub-resource-sync
2026-07-13 12:30:44 +08:00
commit bcbd1bdb22
5748 changed files with 562488 additions and 0 deletions
@@ -0,0 +1,188 @@
# ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========
import pytest
from mirage.commands.builtin.generic_bind.adapter import CommandIO
from mirage.commands.builtin.generic_bind.builders.common import (
dir_refusing_read, split_readable)
from mirage.types import FileStat, FileType, PathSpec
def _ops(missing: set[str],
implicit_dirs: set[str] | None = None,
explicit_dirs: set[str] | None = None) -> CommandIO:
dirs = implicit_dirs or set()
typed = explicit_dirs or set()
async def stat(_accessor, path, _index):
if path.virtual in missing or path.virtual in dirs:
raise FileNotFoundError(path.virtual)
if path.virtual in typed:
return FileStat(name=path.virtual, type=FileType.DIRECTORY)
return FileStat(name=path.virtual, size=0)
async def readdir(_accessor, path, _index):
target = path.virtual.rstrip("/") or "/"
entries = [d for d in dirs if (d.rsplit("/", 1)[0] or "/") == target]
if path.virtual in dirs:
entries.append(path.virtual.rstrip("/") + "/child.txt")
return entries
async def read_stream(_accessor, _path, _index):
yield b"data"
async def unused(*_args):
raise AssertionError("not used")
return CommandIO(readdir=readdir,
read_bytes=unused,
read_stream=read_stream,
stat=stat,
is_mounted=lambda _a: True)
@pytest.mark.asyncio
async def test_split_readable_keeps_order_and_reports_missing():
paths = [
PathSpec.from_str_path("/m1.txt"),
PathSpec.from_str_path("/f.txt"),
PathSpec.from_str_path("/m2.txt"),
]
good, err = await split_readable(_ops({"/m1.txt", "/m2.txt"}), None, paths,
None, "cat")
assert [p.virtual for p in good] == ["/f.txt"]
assert err == (b"cat: /m1.txt: No such file or directory\n"
b"cat: /m2.txt: No such file or directory\n")
@pytest.mark.asyncio
async def test_split_readable_reports_implicit_dir_as_eisdir():
ops = _ops(set(), implicit_dirs={"/sub"})
good, err = await split_readable(ops, None,
[PathSpec.from_str_path("/sub")], None,
"cat")
assert good == []
assert err == b"cat: /sub: Is a directory\n"
@pytest.mark.asyncio
async def test_split_readable_ignores_fabricated_children():
# Synthetic hierarchies (postgres schema level) answer a readdir of
# any missing name with fabricated children; only the parent listing
# decides, so the original ENOENT stands.
async def stat(_accessor, path, _index):
raise FileNotFoundError(path.virtual)
async def readdir(_accessor, path, _index):
target = path.virtual.rstrip("/") or "/"
if target == "/":
return ["/real.txt"]
return [f"{target}/tables", f"{target}/views"]
async def unused(*_args):
raise AssertionError("not used")
ops = CommandIO(readdir=readdir,
read_bytes=unused,
read_stream=unused,
stat=stat,
is_mounted=lambda _a: True)
good, err = await split_readable(ops, None,
[PathSpec.from_str_path("/nope.txt")],
None, "cat")
assert good == []
assert err == b"cat: /nope.txt: No such file or directory\n"
@pytest.mark.asyncio
async def test_split_readable_probe_swallows_driver_errors():
# A backend whose readdir raises a non-FS driver error for missing
# names (lancedb: "Table ... was not found") must not leak it through
# the probe; the original ENOENT stands.
async def stat(_accessor, path, _index):
raise FileNotFoundError(path.virtual)
async def readdir(_accessor, path, _index):
raise ValueError("Table 'nope.txt' was not found")
async def unused(*_args):
raise AssertionError("not used")
ops = CommandIO(readdir=readdir,
read_bytes=unused,
read_stream=unused,
stat=stat,
is_mounted=lambda _a: True)
good, err = await split_readable(ops, None,
[PathSpec.from_str_path("/nope.txt")],
None, "wc")
assert good == []
assert err == b"wc: /nope.txt: No such file or directory\n"
@pytest.mark.asyncio
async def test_split_readable_reports_stat_typed_dir_as_eisdir():
ops = _ops(set(), explicit_dirs={"/sub"})
good, err = await split_readable(ops, None,
[PathSpec.from_str_path("/sub")], None,
"head")
assert good == []
assert err == b"head: /sub: Is a directory\n"
@pytest.mark.asyncio
async def test_dir_refusing_read_raises_eisdir_for_dirs():
ops = _ops(set(), implicit_dirs={"/sub"})
read = dir_refusing_read(ops, None)
with pytest.raises(IsADirectoryError):
async for _ in read(None, PathSpec.from_str_path("/sub")):
raise AssertionError("no data expected")
@pytest.mark.asyncio
async def test_dir_refusing_read_streams_files():
ops = _ops(set())
read = dir_refusing_read(ops, None)
chunks = [c async for c in read(None, PathSpec.from_str_path("/f.txt"))]
assert chunks == [b"data"]
@pytest.mark.asyncio
async def test_split_readable_all_good_no_stderr():
paths = [PathSpec.from_str_path("/f.txt")]
good, err = await split_readable(_ops(set()), None, paths, None, "head")
assert [p.virtual for p in good] == ["/f.txt"]
assert err == b""
@pytest.mark.asyncio
async def test_split_readable_propagates_non_fs_errors():
async def stat(_accessor, _path, _index):
raise RuntimeError("backend broke")
async def unused(*_args):
raise AssertionError("not used")
ops = CommandIO(readdir=unused,
read_bytes=unused,
read_stream=unused,
stat=stat,
is_mounted=lambda _a: True)
with pytest.raises(RuntimeError):
await split_readable(ops, None, [PathSpec.from_str_path("/f.txt")],
None, "cat")
@@ -0,0 +1,117 @@
# ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========
import pytest
from mirage.commands.builtin.generic_bind.adapter import CommandIO
from mirage.commands.builtin.generic_bind.builders.find import find
from mirage.types import FileStat, FileType, PathSpec
TREE = {
"/mnt": ["/mnt/table1", "/mnt/notes.txt"],
"/mnt/table1": ["/mnt/table1/rows.jsonl"],
}
DIRS = {"/mnt", "/mnt/table1"}
def _ops(stat_calls: list[str], is_dir_name=None, find_op=None) -> CommandIO:
async def readdir(_accessor, path, _index):
return TREE.get(path.virtual.rstrip("/") or "/", [])
async def stat(_accessor, path, _index):
stat_calls.append(path.virtual)
if path.virtual not in TREE and path.virtual not in TREE.get(
"/mnt", []) and path.virtual != "/mnt/table1/rows.jsonl":
raise FileNotFoundError(path.virtual)
if path.virtual in DIRS:
return FileStat(name=path.virtual, type=FileType.DIRECTORY)
return FileStat(name=path.virtual, size=3)
async def read_stream(_accessor, _path, _index):
yield b"data"
async def unused(*_args):
raise AssertionError("not used")
return CommandIO(readdir=readdir,
read_bytes=unused,
read_stream=read_stream,
stat=stat,
is_mounted=lambda _a: True,
local=False,
is_dir_name=is_dir_name,
find=find_op)
def _root() -> PathSpec:
return PathSpec(virtual="/mnt",
directory="/mnt",
resolved=False,
resource_path="")
async def _lines(ops: CommandIO) -> list[str]:
stdout, _io = await find(ops, None, [_root()])
data = stdout if isinstance(stdout, bytes) else b""
return data.decode().splitlines()
@pytest.mark.asyncio
async def test_walk_without_hint_stats_children():
stat_calls: list[str] = []
ops = _ops(stat_calls)
lines = await _lines(ops)
assert "/mnt/notes.txt" in lines
assert "/mnt/table1/rows.jsonl" in lines
assert "/mnt/table1" in lines
# no hint: every child entry is stat'ed to classify it
assert len(stat_calls) > 1
@pytest.mark.asyncio
async def test_is_dir_name_hint_skips_child_stats():
stat_calls: list[str] = []
ops = _ops(stat_calls,
is_dir_name=lambda _a, name: name.rstrip("/") in DIRS)
lines = await _lines(ops)
assert "/mnt/notes.txt" in lines
assert "/mnt/table1/rows.jsonl" in lines
# hint answers directory-ness by name; only the search root is stat'ed
assert stat_calls == ["/mnt"]
@pytest.mark.asyncio
async def test_walk_honors_multiple_start_points():
stat_calls: list[str] = []
ops = _ops(stat_calls)
roots = [
PathSpec(virtual="/mnt/table1",
directory="/mnt/table1",
resolved=False,
resource_path="table1"),
PathSpec(virtual="/mnt/notes.txt",
directory="/mnt",
resolved=False,
resource_path="notes.txt"),
]
stdout, _io = await find(ops, None, roots)
data = stdout if isinstance(stdout, bytes) else b""
lines = data.decode().splitlines()
# GNU find walks every start point in operand order
assert "/mnt/table1/rows.jsonl" in lines
assert "/mnt/notes.txt" in lines
assert lines.index("/mnt/table1/rows.jsonl") < lines.index(
"/mnt/notes.txt")
@@ -0,0 +1,105 @@
# ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========
import pytest
from mirage.accessor.base import NOOPAccessor
from mirage.commands.builtin.generic_bind.adapter import make_resolve_glob
from mirage.types import PathSpec
TREE = {
"/notion/pages": [
"/notion/pages/Demo_page__uuid1",
"/notion/pages/Roadmap__uuid2",
],
"/notion/pages/Demo_page__uuid1": [
"/notion/pages/Demo_page__uuid1/page.md",
"/notion/pages/Demo_page__uuid1/page.json",
],
"/notion/pages/Roadmap__uuid2": [
"/notion/pages/Roadmap__uuid2/page.json",
],
}
async def fake_readdir(accessor, path, index=None):
key = path.virtual.rstrip("/") or "/"
if key not in TREE:
raise FileNotFoundError(key)
return TREE[key]
def glob_spec(virtual: str, prefix: str) -> PathSpec:
last_slash = virtual.rfind("/")
return PathSpec(
virtual=virtual,
directory=virtual[:last_slash + 1],
resource_path=virtual[len(prefix):].strip("/"),
pattern=virtual[last_slash + 1:],
resolved=False,
)
@pytest.mark.asyncio
async def test_resolve_glob_mid_path_pattern():
resolve = make_resolve_glob(fake_readdir)
spec = glob_spec("/notion/pages/Demo_page__*/page.md", "/notion")
result = await resolve(NOOPAccessor(), [spec], None)
assert [p.virtual
for p in result] == ["/notion/pages/Demo_page__uuid1/page.md"]
@pytest.mark.asyncio
async def test_resolve_glob_last_component():
resolve = make_resolve_glob(fake_readdir)
spec = glob_spec("/notion/pages/Demo*", "/notion")
result = await resolve(NOOPAccessor(), [spec], None)
assert [p.virtual for p in result] == ["/notion/pages/Demo_page__uuid1"]
@pytest.mark.asyncio
async def test_resolve_glob_passthrough():
resolve = make_resolve_glob(fake_readdir)
resolved_spec = PathSpec.from_str_path("/notion/pages/Roadmap__uuid2",
"pages/Roadmap__uuid2")
result = await resolve(NOOPAccessor(), ["text", resolved_spec], None)
assert result[0].virtual == "text"
assert result[1] is resolved_spec
@pytest.mark.asyncio
async def test_resolve_glob_truncates(caplog):
resolve = make_resolve_glob(fake_readdir, max_glob_matches=1)
spec = glob_spec("/notion/pages/*", "/notion")
result = await resolve(NOOPAccessor(), [spec], None)
assert len(result) == 1
@pytest.mark.asyncio
async def test_resolve_glob_zero_match_word_keeps_literal():
resolve = make_resolve_glob(fake_readdir)
spec = glob_spec("/notion/pages/*.nope", "/notion")
out = await resolve(NOOPAccessor(), [spec], None)
assert len(out) == 1
assert out[0].virtual == "/notion/pages/*.nope"
assert out[0].pattern is None
assert out[0].resolved
@pytest.mark.asyncio
async def test_resolve_glob_zero_match_dir_shape_stays_empty():
resolve = make_resolve_glob(fake_readdir)
spec = glob_spec("/notion/pages/*.nope", "/notion").dir
out = await resolve(NOOPAccessor(), [spec], None)
assert out == []
@@ -0,0 +1,123 @@
# ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========
import pytest
from mirage.cache.context import push_cache_manager
from mirage.cache.file.ram import RAMFileCacheStore
from mirage.cache.manager import CacheManager
from mirage.commands.builtin.generic_bind.adapter import CommandIO
from mirage.commands.builtin.generic_bind.factory import with_read_cache
from mirage.types import PathSpec
from mirage.utils.key_prefix import mount_key
class _CountingBackend:
def __init__(self, data: bytes) -> None:
self.data = data
self.stream_calls = 0
self.bytes_calls = 0
async def read_stream(self, accessor, path, *args, **kwargs):
self.stream_calls += 1
yield self.data
async def read_bytes(self, accessor, path, *args, **kwargs) -> bytes:
self.bytes_calls += 1
return self.data
async def _noop_readdir(accessor, path, index=None) -> list[str]:
return []
async def _noop_stat(accessor, path, index=None):
return None
def _ops(backend: _CountingBackend) -> CommandIO:
return CommandIO(
readdir=_noop_readdir,
read_bytes=backend.read_bytes,
read_stream=backend.read_stream,
stat=_noop_stat,
is_mounted=lambda a: True,
local=False,
)
def _spec() -> PathSpec:
return PathSpec(resource_path=mount_key("/s3/a.txt", "/s3/"),
virtual="/s3/a.txt",
directory="/s3/")
async def _drain(source) -> bytes:
return b"".join([c async for c in source])
@pytest.mark.asyncio
async def test_warm_read_stream_serves_cache_without_backend():
backend = _CountingBackend(b"payload")
cache = RAMFileCacheStore()
await cache.set("/s3/a.txt", b"payload")
manager = CacheManager(cache, None, "/s3/", True)
ops = with_read_cache(_ops(backend))
prev = push_cache_manager(manager)
try:
out = await _drain(ops.read_stream(None, _spec()))
finally:
push_cache_manager(prev)
assert out == b"payload"
assert backend.stream_calls == 0
@pytest.mark.asyncio
async def test_warm_read_bytes_serves_cache_without_backend():
backend = _CountingBackend(b"payload")
cache = RAMFileCacheStore()
await cache.set("/s3/a.txt", b"payload")
manager = CacheManager(cache, None, "/s3/", True)
ops = with_read_cache(_ops(backend))
prev = push_cache_manager(manager)
try:
out = await ops.read_bytes(None, _spec())
finally:
push_cache_manager(prev)
assert out == b"payload"
assert backend.bytes_calls == 0
@pytest.mark.asyncio
async def test_cold_read_falls_through_to_backend():
backend = _CountingBackend(b"payload")
manager = CacheManager(RAMFileCacheStore(), None, "/s3/", True)
ops = with_read_cache(_ops(backend))
prev = push_cache_manager(manager)
try:
out = await _drain(ops.read_stream(None, _spec()))
finally:
push_cache_manager(prev)
assert out == b"payload"
assert backend.stream_calls == 1
@pytest.mark.asyncio
async def test_no_manager_falls_through_to_backend():
backend = _CountingBackend(b"payload")
ops = with_read_cache(_ops(backend))
out = await _drain(ops.read_stream(None, _spec()))
assert out == b"payload"
assert backend.stream_calls == 1
@@ -0,0 +1,297 @@
# ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========
import pytest
from mirage.cache.index import IndexEntry
from mirage.cache.index.ram import RAMIndexCacheStore
from mirage.commands.builtin.generic_bind.provision import (
default_provision, exact_zero_provision, index_hit_read_provision,
make_copy_provision, make_file_read_provision, make_head_tail_provision,
make_search_provision, make_transform_provision, metadata_provision,
pure_provision, write_metadata_provision)
from mirage.commands.builtin.ram import COMMANDS as RAM_COMMANDS
from mirage.provision import Precision
from mirage.types import FileStat, FileType, PathSpec
from mirage.utils.key_prefix import mount_key
SIZES = {
"/data/known.txt": 5,
"/data/big.txt": 100,
"/data/tree/a.txt": 7,
"/data/tree/skip.parquet": 900,
"/data/tree/sub/b.txt": 11,
}
DIRS = {"/data/tree", "/data/tree/sub"}
TREE = {
"/data/tree":
["/data/tree/a.txt", "/data/tree/skip.parquet", "/data/tree/sub"],
"/data/tree/sub": ["/data/tree/sub/b.txt"],
}
def _spec(path: str) -> PathSpec:
return PathSpec(resource_path=mount_key(path, "/data"),
virtual=path,
directory=path)
async def _stat(accessor, path, index=None) -> FileStat:
virtual = path.virtual if isinstance(path, PathSpec) else path
if virtual in DIRS:
return FileStat(name=virtual.rsplit("/", 1)[-1],
type=FileType.DIRECTORY)
return FileStat(name=virtual.rsplit("/", 1)[-1],
size=SIZES.get(virtual),
type=FileType.TEXT)
async def _readdir(accessor, path, index=None) -> list[str]:
virtual = path.virtual if isinstance(path, PathSpec) else path
return TREE[virtual]
async def _resolve_glob(accessor, paths, index=None) -> list[PathSpec]:
out = []
for p in paths:
if p.pattern:
out.extend(
_spec(e) for e in TREE.get(p.directory.rstrip("/"), [])
if e.endswith(p.pattern.lstrip("*")))
else:
out.append(p)
return out
def _registered(name: str):
for fn in RAM_COMMANDS:
for rc in getattr(fn, "_registered_commands", []):
if rc.name == name and rc.filetype is None:
return rc
return None
def test_default_provision_families():
assert default_provision("sort", _stat) is not None
assert default_provision("grep", _stat) is not None
assert default_provision("iconv", _stat) is not None
assert default_provision("file", _stat) is not None
assert default_provision("ls", _stat) is metadata_provision
assert default_provision("stat", _stat) is metadata_provision
assert default_provision("du", _stat) is metadata_provision
assert default_provision("gzip", _stat) is not None
assert default_provision("cp", _stat) is not None
assert default_provision("rm", _stat) is write_metadata_provision
assert default_provision("mv", _stat) is None
assert default_provision("tee", _stat) is None
def test_factory_registers_default_provisions():
for name in ("grep", "sort", "ls", "find", "md5", "cp", "gzip", "rm"):
rc = _registered(name)
assert rc is not None, name
assert rc.provision_fn is not None, name
rc = _registered("tee")
assert rc is not None
assert rc.provision_fn is None
@pytest.mark.asyncio
async def test_file_read_known_sizes_exact():
provision = make_file_read_provision(_stat)
result = await provision(
None, [_spec("/data/known.txt"),
_spec("/data/big.txt")],
command="cat")
assert result.precision == Precision.EXACT
assert result.network_read_low == 105
assert result.network_read_high == 105
assert result.read_ops == 2
@pytest.mark.asyncio
async def test_file_read_missing_size_keeps_floor():
provision = make_file_read_provision(_stat)
result = await provision(
None, [_spec("/data/known.txt"),
_spec("/data/chat.jsonl")],
command="cat")
assert result.precision == Precision.UNKNOWN
assert result.network_read_low == 5
assert result.network_read_high == 5
assert result.read_ops == 2
@pytest.mark.asyncio
async def test_head_tail_missing_size_keeps_known_ceiling():
provision = make_head_tail_provision(_stat)
result = await provision(
None, [_spec("/data/known.txt"),
_spec("/data/chat.jsonl")],
command="head")
assert result.precision == Precision.UNKNOWN
assert result.network_read_low == 0
assert result.network_read_high == 5
assert result.read_ops == 2
@pytest.mark.asyncio
async def test_transform_keeps_read_floor_unknown_output():
provision = make_transform_provision(_stat)
result = await provision(None, [_spec("/data/known.txt")], command="gzip")
assert result.precision == Precision.UNKNOWN
assert result.network_read_low == 5
assert result.network_read_high == 5
assert result.read_ops == 1
@pytest.mark.asyncio
async def test_copy_brackets_read_and_write():
provision = make_copy_provision(_stat)
result = await provision(
None, [_spec("/data/known.txt"),
_spec("/data/dest.txt")],
command="cp")
assert result.precision == Precision.RANGE
assert result.network_read_low == 0
assert result.network_read_high == 5
assert result.network_write_low == 0
assert result.network_write_high == 5
assert result.read_ops == 1
@pytest.mark.asyncio
async def test_write_metadata_zero_bytes_recursive_floors():
result = await write_metadata_provision(None, [_spec("/data/known.txt")],
command="rm")
assert result.precision == Precision.EXACT
assert result.network_read_high == 0
assert result.read_ops == 1
recursive = await write_metadata_provision(None,
[_spec("/data/known.txt")],
command="rm",
r=True)
assert recursive.precision == Precision.UNKNOWN
@pytest.mark.asyncio
async def test_pure_provision_zero_exact():
result = await pure_provision(command="seq 3")
assert result.precision == Precision.EXACT
assert result.network_read_high == 0
assert result.read_ops == 0
@pytest.mark.asyncio
async def test_file_read_expands_globs():
provision = make_file_read_provision(_stat, _resolve_glob)
pattern = PathSpec(virtual="/data/tree/*.txt",
directory="/data/tree/",
pattern="*.txt",
resource_path="tree/*.txt")
result = await provision(None, [pattern], command="cat")
assert result.precision == Precision.EXACT
assert result.network_read_high == 7
assert result.read_ops == 1
@pytest.mark.asyncio
async def test_file_read_unmatched_glob_unknown():
provision = make_file_read_provision(_stat, _resolve_glob)
pattern = PathSpec(virtual="/data/tree/*.nope",
directory="/data/tree/",
pattern="*.nope",
resource_path="tree/*.nope")
result = await provision(None, [pattern], command="cat")
assert result.precision == Precision.UNKNOWN
assert result.network_read_high == 0
@pytest.mark.asyncio
async def test_search_recursive_walks_tree_exact():
provision = make_search_provision(_stat, _resolve_glob, _readdir)
result = await provision(None, [_spec("/data/tree")],
"x",
command="grep",
r=True)
assert result.precision == Precision.EXACT
assert result.network_read_high == 18
assert result.read_ops == 2
@pytest.mark.asyncio
async def test_search_recursive_skips_columnar():
provision = make_search_provision(_stat, _resolve_glob, _readdir)
result = await provision(None, [_spec("/data/tree")],
"x",
command="grep",
r=True)
assert result.network_read_high != 918
@pytest.mark.asyncio
async def test_search_without_readdir_keeps_floor():
provision = make_search_provision(_stat, _resolve_glob)
result = await provision(None, [_spec("/data/tree")],
"x",
command="grep",
r=True)
assert result.precision == Precision.UNKNOWN
@pytest.mark.asyncio
async def test_search_recursive_cap_degrades(monkeypatch):
monkeypatch.setattr(
"mirage.commands.builtin.generic_bind.provision.MAX_PLAN_WALK", 2)
provision = make_search_provision(_stat, _resolve_glob, _readdir)
result = await provision(None, [_spec("/data/tree")],
"x",
command="grep",
r=True)
assert result.precision == Precision.UNKNOWN
@pytest.mark.asyncio
async def test_exact_zero_provision_charges_nothing():
result = await exact_zero_provision("find /chat")
assert result.command == "find /chat"
assert result.network_read_low == 0
assert result.network_read_high == 0
assert result.read_ops == 0
assert result.precision == Precision.EXACT
@pytest.mark.asyncio
async def test_index_hit_read_provision_counts_cached_operands():
index = RAMIndexCacheStore()
await index.put("/chat/a.jsonl",
IndexEntry(id="a", name="a.jsonl", resource_type="file"))
paths = [
PathSpec(virtual="/chat/a.jsonl",
directory="/chat",
resource_path="a.jsonl"),
PathSpec(virtual="/chat/missing.jsonl",
directory="/chat",
resource_path="missing.jsonl"),
]
result = await index_hit_read_provision(None, paths, "cat", index)
assert result.read_ops == 1
assert result.network_read_low == 0
assert result.precision == Precision.EXACT
@pytest.mark.asyncio
async def test_index_hit_read_provision_without_paths_is_unknown():
result = await index_hit_read_provision(None, [], "grep x", None)
assert result.precision == Precision.UNKNOWN
@@ -0,0 +1,94 @@
# ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========
from functools import partial
import pytest
from mirage.commands.builtin.generic_bind.adapter import CommandIO
from mirage.commands.builtin.generic_bind.builders.du import du as du_builder
from mirage.commands.builtin.generic_bind.builders.find import \
find as find_builder
from mirage.commands.builtin.utils.wrap import stream_from_bytes
from mirage.io.types import materialize
from mirage.types import FileStat, FileType, PathSpec
_FILES = {
"/g/a.txt": b"alpha\n",
"/g/sub/b.txt": b"bravo\n",
}
_DIRS = {"/g", "/g/sub"}
async def _readdir(accessor, path, index=None):
base = (path.virtual if isinstance(path, PathSpec) else path).rstrip("/")
out = []
for p in list(_FILES) + sorted(_DIRS):
parent = p.rsplit("/", 1)[0] or "/"
if parent == base and p != base:
out.append(p)
return out
async def _stat(accessor, path, index=None):
p = path.virtual if isinstance(path, PathSpec) else path
p = p.rstrip("/") or "/"
if p in _DIRS:
return FileStat(name=p.rsplit("/", 1)[-1], type=FileType.DIRECTORY)
if p in _FILES:
return FileStat(name=p.rsplit("/", 1)[-1],
size=len(_FILES[p]),
type=FileType.TEXT)
raise FileNotFoundError(p)
async def _read(accessor, path, index=None):
p = path.virtual if isinstance(path, PathSpec) else path
return _FILES[p.rstrip("/")]
def _ops() -> CommandIO:
return CommandIO(
readdir=_readdir,
read_bytes=_read,
read_stream=partial(stream_from_bytes, _read),
stat=_stat,
is_mounted=lambda a: True,
local=False,
)
def _spec(original: str) -> PathSpec:
return PathSpec(resource_path=(original).strip("/"),
virtual=original,
directory=original,
resolved=True)
@pytest.mark.asyncio
async def test_find_walks_tree_without_native_find_op():
out, io = await find_builder(_ops(), object(), [_spec("/g")], type="f")
text = (await materialize(out)).decode()
assert "/g/a.txt" in text
assert "/g/sub/b.txt" in text
assert io.exit_code == 0
@pytest.mark.asyncio
async def test_du_walks_tree_without_native_du_op():
out, _ = await du_builder(_ops(), object(), [_spec("/g")], s=True)
text = (await materialize(out)).decode()
# alpha\n (6) + bravo\n (6) = 12 bytes summed by the readdir walk.
assert "12" in text
assert "/g" in text