Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions docs/asset-catalog.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,22 @@ are accepted. The first ABO search retrieves its bounded pinned metadata index;
Search returns bounded summaries and links to detailed records. The
NVIDIA adapter requests no inline previews. Opening a preview is a separate
operation. Search service failures are reported as unavailable/partial results.
An index transfer that exceeds the configured search deadline also reports a
timeout; it does not publish a partial index. Retry or explicitly refresh it
when the source recovers. Cursor pages retain the original query's cost under
A cold index that exceeds the interactive search deadline reports `timeout`.
On current source builds, a supported cold source includes a recovery hint
for the `catalog_refresh` MCP tool. Call it with
`{"source_id": "abo-glb"}`, then repeat the search. The CLI equivalent is
`simscene catalog refresh abo-glb`. The completed refresh installs the
pinned metadata index as a single transaction.

Current source builds give explicit refresh a 60-second download and parsing
budget. Interactive searches default to 12 seconds. Host settings can set
`refresh_deadline_seconds` and `search_deadline_seconds` in the V2 JSON
configuration. For example, with the released dev2 build, a slow cold ABO
connection can use `{"search_deadline_seconds": 45}` in the file pointed to
by `SIMSCENE_V2_CONFIG`. The recorded cold worktop run completed that query
within this budget.

Cursor pages retain the original query's cost under
`budgets.metadata_bytes`; use `budgets.request_metadata_bytes` and
`request_preview_bytes` for per-call transfer accounting. Cached cursor pages
make no network requests.
Expand Down
3 changes: 2 additions & 1 deletion src/simscene/catalog/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
from pathlib import Path

DEFAULTS = {
'schema_version': 1, 'search_deadline_seconds': 12, 'metadata_max_bytes': 32*1024**2,
'schema_version': 1, 'search_deadline_seconds': 12, 'refresh_deadline_seconds': 60,
'metadata_max_bytes': 32*1024**2,
'asset_download_bytes': 1024**3, 'scene_download_bytes': 2*1024**3,
'unpacked_bytes': 4*1024**3, 'staging_bytes': 4*1024**3,
'prepared_cache_bytes': 4*1024**3,
Expand Down
10 changes: 7 additions & 3 deletions src/simscene/catalog/providers/abo.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ def refresh(self):
if not records:
raise MetadataError('ABO metadata index is empty')
identity = self.entry.revision + ':' + hashlib.sha256(payload).hexdigest()
self.check_deadline()
self.store.replace_index(self.source_id, records, identity)
return {'source_id': self.source_id, 'snapshot': identity, 'records': len(records),
'metadata_bytes': len(payload), 'model_bytes': 0,
Expand Down Expand Up @@ -109,12 +110,15 @@ def search(self, request):
if self.snapshot == 'index_not_refreshed':
self.refresh()
self.check_deadline()
records = self.store.search(self.source_id, request.query, limit=100)
records, snapshot = self.store.search(self.source_id, request.query, limit=100,
revision=self.entry.revision, include_snapshot=True)
if not snapshot or not snapshot.startswith(self.entry.revision + ':'):
raise MetadataError('ABO metadata index changed during search')
self.check_deadline()
metadata_bytes = sum(entry.get('bytes', 0) for entry in self.ledger[start:]
if entry.get('category') == 'metadata')
return ProviderPage(records, self.snapshot, bytes_read=metadata_bytes,
warnings=(() if self.store.fts else ('fts5_unavailable',)))
return ProviderPage(records, snapshot, bytes_read=metadata_bytes,
warnings=(() if self.store.fts else ('fts5_unavailable',)), indexed=True)

def resolve(self, ref):
if ref.source_id != self.source_id:
Expand Down
9 changes: 6 additions & 3 deletions src/simscene/catalog/providers/artvip.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,11 +139,14 @@ def search(self, request):
start = len(self.ledger)
if self.snapshot == 'index_not_refreshed':
self.refresh()
records = self.store.search(self.source_id, request.query, limit=100, revision=self.entry.revision)
records, snapshot = self.store.search(self.source_id, request.query, limit=100,
revision=self.entry.revision, include_snapshot=True)
if not snapshot or not snapshot.startswith(self.prefix) or not snapshot.endswith(self.suffix):
raise MetadataError('ArtVIP metadata index changed during search')
self.check_deadline()
count = sum(item.get('bytes', 0) for item in self.ledger[start:] if item.get('category') == 'metadata')
return ProviderPage(tuple(self._reproject(record) for record in records), self.snapshot,
bytes_read=count, warnings=(() if self.store.fts else ('fts5_unavailable',)))
return ProviderPage(tuple(self._reproject(record) for record in records), snapshot,
bytes_read=count, warnings=(() if self.store.fts else ('fts5_unavailable',)), indexed=True)

def resolve(self, ref):
if ref.source_id != self.source_id or ref.revision != self.entry.revision:
Expand Down
1 change: 1 addition & 0 deletions src/simscene/catalog/providers/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ class ProviderPage:
snapshot: str
bytes_read: int = 0
warnings: tuple[str, ...] = ()
indexed: bool = False


class Provider:
Expand Down
3 changes: 3 additions & 0 deletions src/simscene/catalog/providers/factory.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
"""Explicit adapter selection; an unknown adapter can never become NVIDIA search."""


INDEX_REFRESH_ADAPTERS = frozenset({'abo', 'hf_manifest', 'usdcraft', 'http_assets'})


def make_provider(store, source, config):
cap=config['metadata_max_bytes']
if source.adapter=='nvidia':
Expand Down
15 changes: 12 additions & 3 deletions src/simscene/catalog/providers/hf_manifest.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,10 @@ def __init__(self,store,source,*,base_url='https://huggingface.co',max_index_byt
@property
def snapshot(self):
value=self.store.snapshot(self.source_id)
return value if value and value.startswith(self.entry.revision+':') else 'index_not_refreshed'
return value if self._valid_snapshot(value) else 'index_not_refreshed'

def _valid_snapshot(self, snapshot):
return bool(snapshot and snapshot.startswith(self.entry.revision+':'))

def url(self,path):
return self.base_url+'/datasets/'+self.source.repository+'/resolve/'+self.entry.revision+'/'+quote(safe_path(path),safe='/')
Expand Down Expand Up @@ -88,6 +91,7 @@ def refresh(self):
raise MetadataError('manifest metadata schema changed; previous index preserved') from None
if not records:raise MetadataError('manifest metadata is empty')
identity=self.snapshot_identity(payload)
self.check_deadline()
self.store.replace_index(self.source_id,records,identity)
return {'source_id':self.source_id,'snapshot':identity,'records':len(records),'metadata_bytes':len(payload),'model_bytes':0,
'text_index':'fts5' if self.store.fts else 'bounded_text_fallback'}
Expand Down Expand Up @@ -125,9 +129,14 @@ def _record(self,row):
def search(self,request):
self.check_deadline();start=len(self.ledger)
if self.snapshot=='index_not_refreshed':self.refresh()
records=self.store.search(self.source_id,request.query,limit=100,revision=self.entry.revision);self.check_deadline()
records, snapshot = self.store.search(self.source_id, request.query, limit=100,
revision=self.entry.revision, include_snapshot=True)
if not self._valid_snapshot(snapshot):
raise MetadataError('manifest metadata index changed during search')
self.check_deadline()
count=sum(entry.get('bytes',0) for entry in self.ledger[start:] if entry.get('category')=='metadata')
return ProviderPage(records,self.snapshot,bytes_read=count,warnings=(() if self.store.fts else ('fts5_unavailable',)))
return ProviderPage(records, snapshot, bytes_read=count,
warnings=(() if self.store.fts else ('fts5_unavailable',)), indexed=True)

def resolve(self,ref):
if ref.source_id!=self.source_id:raise ValueError('wrong manifest source')
Expand Down
10 changes: 8 additions & 2 deletions src/simscene/catalog/providers/http_assets.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,15 +125,21 @@ def refresh(self):
try:records.append(polyhaven_record(identity,*responses,kind='hdri' if category=='hdris' else 'material'))
except ValueError as error:raise MetadataError(str(error)) from None
snapshot=hashlib.sha256(''.join(hashes).encode()).hexdigest()
self.check_deadline()
self.store.replace_index(self.source_id,records,snapshot)
return {'source_id':self.source_id,'snapshot':snapshot,'records':len(records),'metadata_bytes':total,'model_bytes':0}

def search(self, request):
from .base import ProviderPage
from ..network import MetadataError
start=len(self.ledger);self.check_deadline()
if self.snapshot=='index_not_refreshed':self.refresh()
return ProviderPage(tuple(self.store.search(self.source_id,request.query,limit=100)),self.snapshot,
sum(item.get('bytes',0) for item in self.ledger[start:]),('selected_metadata_list_only',))
records, snapshot = self.store.search(self.source_id, request.query, limit=100, include_snapshot=True)
if not snapshot:
raise MetadataError('Poly Haven metadata index changed during search')
self.check_deadline()
return ProviderPage(records, snapshot, sum(item.get('bytes',0) for item in self.ledger[start:]),
('selected_metadata_list_only',), indexed=True)

def resolve(self, ref):
if ref.source_id!=self.source_id:raise ValueError('wrong source for Poly Haven provider')
Expand Down
13 changes: 4 additions & 9 deletions src/simscene/catalog/providers/simready_package.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,9 @@ def __init__(self,store,source,**kwargs):
super().__init__(store,source,**kwargs)
if self.entry.path!='manifest.csv' or self.entry.format!='csv':raise ValueError('USDCraft requires pinned manifest.csv')

@property
def snapshot(self):
value=super().snapshot
# Persist the projection version itself. Presence of fields cannot tell
# whether an older projector computed articulated contradictions safely.
return value if value.endswith(USDCRAFT_PROJECTION_SUFFIX) else 'index_not_refreshed'
def _valid_snapshot(self, snapshot):
# The version identifies the projector that computed these facts.
return super()._valid_snapshot(snapshot) and snapshot.endswith(USDCRAFT_PROJECTION_SUFFIX)

def snapshot_identity(self, payload):
# The projection and its records are published in one SQLite transaction.
Expand All @@ -42,10 +39,8 @@ def reproject(self, record):

def search(self, request):
page = super().search(request)
if page.snapshot == 'index_not_refreshed':
raise MetadataError('USDCraft metadata index changed during search')
return ProviderPage(tuple(self.reproject(record) for record in page.items), page.snapshot,
bytes_read=page.bytes_read, warnings=page.warnings)
bytes_read=page.bytes_read, warnings=page.warnings, indexed=True)

def resolve(self, ref):
if ref.source_id != self.source_id:
Expand Down
19 changes: 15 additions & 4 deletions src/simscene/catalog/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import json
import time
from .models import SearchPage, SearchRequest, stable_hash
from .providers.factory import INDEX_REFRESH_ADAPTERS
from .network import MetadataDeadline, MetadataError
from .registry import load_registry
from .store import CatalogStore
Expand Down Expand Up @@ -215,15 +216,20 @@ def search_assets(request, *, registry=None, providers=None, index_directory=Non
statuses[source.source_id] = {'status': 'ok', 'candidates': len(page.items),
'experimental': source.state != 'enabled',
'warnings': list(page.warnings)}
source_records = []
matches = []
for rank, record in enumerate(page.items):
if record.ref.source_id != source.source_id:
raise ValueError('provider returned a foreign source')
decision = constraint_decision(record, request)
if decision['include']:
detail = store.remember(record)
source_records.append(_summary(record, decision, detail, source.state != 'enabled', rank))
records.extend(source_records)
matches.append((rank, record, decision))
if page.indexed:
# A concurrent refresh may have replaced these rows already.
details = [store.put_detail(record) for _, record, _ in matches]
else:
details = store.remember_many(record for _, record, _ in matches)
records.extend([_summary(record, decision, detail, source.state != 'enabled', rank)
for (rank, record, decision), detail in zip(matches, details)])
except MetadataDeadline:
statuses[source.source_id] = {'status': 'timeout'}
except MetadataError as error:
Expand All @@ -236,6 +242,11 @@ def search_assets(request, *, registry=None, providers=None, index_directory=Non
statuses[futures[future].source_id] = {'status': 'timeout'}
finally:
executor.shutdown(wait=False, cancel_futures=True)
for source in sources:
source_status = statuses[source.source_id]
if (source_status['status'] == 'timeout' and source.adapter in INDEX_REFRESH_ADAPTERS
and versions.get(source.source_id) == 'index_not_refreshed'):
source_status['recovery'] = {'tool': 'catalog_refresh', 'source_id': source.source_id}
successes = sum(s['status'] == 'ok' for s in statuses.values())
status = 'ok' if statuses and successes == len(statuses) else 'partial' if successes else 'unavailable'
# Only identical immutable refs are deduplicated; similar titles/geometries
Expand Down
20 changes: 13 additions & 7 deletions src/simscene/catalog/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,16 @@ def refresh(source_id):
from .registry import load_registry
from .config import read
from .store import CatalogStore
from .providers.factory import make_provider
config = read(); source = load_registry(config.get('registry_path')).get(source_id)
if source.adapter not in {'abo','hf_manifest','usdcraft','http_assets'}:
raise ValueError('source has no downloadable metadata index; search the live service directly')
provider = make_provider(CatalogStore(config['index_directory']),source,config)
ledger = []; provider.configure(time.monotonic()+config['search_deadline_seconds'], ledger)
return dict(provider.refresh(), requests=ledger)
from .providers.factory import INDEX_REFRESH_ADAPTERS, make_provider

if not isinstance(source_id, str) or not source_id.strip():
raise ValueError('refresh requires a catalog source ID')
config = read()
source, = load_registry(config.get('registry_path')).select((source_id,))
if source.adapter not in INDEX_REFRESH_ADAPTERS:
raise ValueError('source has no explicit index refresh; use catalog search for this source')
provider = make_provider(CatalogStore(config['index_directory']), source, config)
seconds = config['refresh_deadline_seconds']
ledger = []
provider.configure(time.monotonic() + seconds, ledger)
return dict(provider.refresh(), requests=ledger, deadline_seconds=seconds)
44 changes: 30 additions & 14 deletions src/simscene/catalog/store.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,13 +59,23 @@ def put_detail(self, record):
return self.write_document('details', identity, record.to_dict())

def remember(self, record):
key = stable_hash(record.ref)
text = ' '.join([record.title, record.category or '', *record.tags])
return self.remember_many((record,))[0]

def remember_many(self, records):
"""Persist one search provider's candidates in a single write transaction."""
records = tuple(records)
if not records:
return ()
rows = [self._record_row(record) for record in records]
with self.connect() as db:
db.execute('INSERT OR REPLACE INTO records VALUES (?,?,?,?,?,?)',
(key, record.ref.source_id, record.ref.asset_id, record.ref.revision,
canonical_json(record, exclude_volatile=False), text))
return self.put_detail(record)
db.executemany('INSERT OR REPLACE INTO records VALUES (?,?,?,?,?,?)', rows)
return tuple(self.put_detail(record) for record in records)

@staticmethod
def _record_row(record):
text = ' '.join([record.title, record.category or '', *record.tags])
return (stable_hash(record.ref), record.ref.source_id, record.ref.asset_id, record.ref.revision,
canonical_json(record, exclude_volatile=False), text)

def get(self, ref, *, require_snapshot_prefix=None, require_snapshot_suffix=None):
key = stable_hash(ref)
Expand Down Expand Up @@ -94,10 +104,7 @@ def replace_index(self, source_id, records, snapshot):
for record in records:
if record.ref.source_id != source_id:
raise ValueError('index contains an asset from another source')
key = stable_hash(record.ref)
text = ' '.join([record.title, record.category or '', *record.tags])
prepared.append((key, source_id, record.ref.asset_id, record.ref.revision,
canonical_json(record, exclude_volatile=False), text))
prepared.append(self._record_row(record))
if len({r[0] for r in prepared}) != len(prepared):
raise ValueError('duplicate asset reference in index')
with self.connect() as db:
Expand All @@ -108,12 +115,20 @@ def replace_index(self, source_id, records, snapshot):
db.executemany('INSERT INTO record_fts VALUES (?,?,?)', [(r[0], r[1], r[5]) for r in prepared])
db.execute('INSERT OR REPLACE INTO indexes VALUES (?,?)', (source_id, snapshot))

def search(self, source_id, query, *, limit=100, revision=None):
def search(self, source_id, query, *, limit=100, revision=None, include_snapshot=False):
"""Read candidates and, when requested, their marker in one SQLite snapshot."""
tokens = re.findall(r'[^\W_]+', query, re.UNICODE)[:16]
if not tokens:
if not tokens and not include_snapshot:
return ()
marker = None
with self.connect() as db:
if self.fts:
if include_snapshot:
db.execute('BEGIN')
row = db.execute('SELECT snapshot FROM indexes WHERE source=?', (source_id,)).fetchone()
marker = row[0] if row else None
if not tokens:
rows = ()
elif self.fts:
match = ' OR '.join('"' + t.replace('"', '""') + '"' for t in tokens)
rows = db.execute('SELECT r.payload FROM record_fts f JOIN records r ON r.key=f.key WHERE record_fts MATCH ? AND r.source=?' +
(' AND r.revision=?' if revision is not None else '') + ' ORDER BY rank, r.asset_id LIMIT ?',
Expand All @@ -124,4 +139,5 @@ def search(self, source_id, query, *, limit=100, revision=None):
rows = db.execute(f'SELECT payload FROM records WHERE source=? AND ({clauses})' +
(' AND revision=?' if revision is not None else '') + ' ORDER BY asset_id LIMIT ?',
(source_id, *terms, *([revision] if revision is not None else []), limit)).fetchall()
return tuple(AssetRecord.from_dict(json.loads(row[0])) for row in rows)
records = tuple(AssetRecord.from_dict(json.loads(row[0])) for row in rows)
return (records, marker) if include_snapshot else records
3 changes: 2 additions & 1 deletion src/simscene/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import sys
from pathlib import Path
from .assets import USDSearch, SearchError
from .catalog.network import MetadataError
from .scene import SceneError

def _load(path):
Expand Down Expand Up @@ -300,7 +301,7 @@ def main():
result = probe()
result["usd_search_url"] = client.base_url
print(json.dumps(result, ensure_ascii=False, indent=2))
except (SearchError, SceneError, ValueError, OSError, KeyError, TypeError) as e:
except (SearchError, MetadataError, SceneError, ValueError, OSError, KeyError, TypeError) as e:
print(str(e), file=sys.stderr)
return 1
return 0
Expand Down
Loading
Loading