gabriel / musehub public
musehub_wire_fetch.py python
937 lines 34.0 KB
Raw
sha256:f99af7b1a7f36c4d537d1c630d4b71fc39222b1255f82e930929e2fc89015e11 fix: relax browse_repo perf budget to 500ms — 200ms was too… Sonnet 4.6 99 days ago
1 """Fetch path — wire_fetch_presign, wire_fetch_mpack, wire_fetch, process_mpack_gc_job."""
2
3 import asyncio
4 import hashlib
5 import logging
6 import msgpack as _msgpack
7 import time as _time_module
8 from datetime import datetime, timezone
9 from typing import TypedDict
10
11 from sqlalchemy import func, select, text as _sa_text
12 from sqlalchemy.dialects.postgresql import insert as _pg_insert
13 from sqlalchemy.ext.asyncio import AsyncSession
14
15 from musehub.db.musehub_repo_models import (
16 MusehubBranch,
17 MusehubCommit,
18 MusehubCommitGraph,
19 MusehubMPackIndex,
20 MusehubObject,
21 MusehubObjectRef,
22 MusehubRepo,
23 MusehubSnapshot,
24 )
25 from musehub.models.wire import WireFetchRequest
26 from muse.core.types import blob_id
27 from musehub.storage import get_backend
28
29 from musehub.services.musehub_wire_shared import (
30 FetchMPackResult,
31 FetchNotIndexedError,
32 FetchPresignResult,
33 MPackValidationError,
34 _reconstruct_manifest,
35 _snap_row_to_wire,
36 _to_wire_commit,
37 _utc_now,
38 logger,
39 )
40
41
42 type _CommitDeltaMap = dict[str, MusehubCommitGraph | MusehubCommit]
43
44
45 async def _walk_commit_delta(
46 session: AsyncSession,
47 want: list[str] | set[str],
48 have: list[str] | set[str],
49 ) -> _CommitDeltaMap:
50 _wcd_t0 = _time_module.perf_counter()
51 _want_list = list(want)
52 _have_list = list(have)
53 logger.info("[_walk_commit_delta] START want=%d have=%d want_ids=%s",
54 len(_want_list), len(_have_list),
55 [cid[:16] for cid in _want_list[:5]])
56
57 have_set: frozenset[str] = frozenset(_have_list)
58 starts = [cid for cid in _want_list if cid not in have_set]
59 if not starts:
60 logger.info("[_walk_commit_delta] SKIP — all want in have, 0ms")
61 return {}
62
63 if True: # fast path always active — commit graph is global (no repo_id)
64 from sqlalchemy import func as _func
65
66 want_gen_q = await session.execute(
67 select(_func.max(MusehubCommitGraph.generation))
68 .where(MusehubCommitGraph.commit_id.in_(starts))
69 )
70 _want_gen_raw = want_gen_q.scalar()
71 max_want_gen: int = _want_gen_raw or 0
72
73 _missing_from_graph: list[str] = []
74 _found_in_graph: list[tuple[str, int]] = []
75 for _scid in starts[:10]:
76 _sg = await session.execute(
77 select(MusehubCommitGraph.generation)
78 .where(MusehubCommitGraph.commit_id == _scid)
79 )
80 _sg_val = _sg.scalar_one_or_none()
81 if _sg_val is None:
82 _missing_from_graph.append(_scid[:16])
83 else:
84 _found_in_graph.append((_scid[:16], _sg_val))
85 logger.info(
86 "[_walk_commit_delta] want_gen_raw=%s max_want_gen=%d "
87 "starts_in_graph=%s starts_missing_from_graph=%s",
88 _want_gen_raw, max_want_gen, _found_in_graph, _missing_from_graph,
89 )
90
91 min_have_gen: int = -1
92 if have_set:
93 have_gen_q = await session.execute(
94 select(_func.max(MusehubCommitGraph.generation))
95 .where(MusehubCommitGraph.commit_id.in_(list(have_set)))
96 )
97 min_have_gen = have_gen_q.scalar() or -1
98
99 range_q = await session.execute(
100 select(
101 MusehubCommitGraph.commit_id,
102 MusehubCommitGraph.parent_ids,
103 MusehubCommitGraph.snapshot_id,
104 )
105 .where(MusehubCommitGraph.generation > min_have_gen)
106 .where(MusehubCommitGraph.generation <= max_want_gen)
107 )
108 graph_map: dict[str, tuple[list[str], str | None]] = {
109 cid: (pids or [], sid) for cid, pids, sid in range_q
110 }
111 logger.info(
112 "[_walk_commit_delta] range_scan gen=(%d,%d] returned %d rows "
113 "starts_in_map=%s",
114 min_have_gen, max_want_gen, len(graph_map),
115 [cid[:16] for cid in starts if cid in graph_map],
116 )
117
118 visited_mem: set[str] = set(have_set)
119 frontier_mem = [cid for cid in starts if cid not in visited_mem]
120 reachable_cids: set[str] = set()
121 while frontier_mem:
122 next_mem: list[str] = []
123 for cid in frontier_mem:
124 if cid in visited_mem:
125 continue
126 visited_mem.add(cid)
127 reachable_cids.add(cid)
128 pids_for_cid, _ = graph_map.get(cid, ([], None))
129 for p in pids_for_cid:
130 if p not in visited_mem and p not in have_set:
131 next_mem.append(p)
132 frontier_mem = next_mem
133
134 from types import SimpleNamespace as _SN
135 needed_graph: dict[str, _SN] = {}
136 for cid in reachable_cids:
137 pids_ns, sid_ns = graph_map.get(cid, ([], None))
138 needed_graph[cid] = _SN(commit_id=cid, snapshot_id=sid_ns, parent_ids=pids_ns)
139
140 _wcd_elapsed = (_time_module.perf_counter() - _wcd_t0) * 1000
141 logger.info(
142 "[_walk_commit_delta] DONE (graph) commits=%d elapsed=%.1fms (%.3fms/commit) "
143 "gen_range=(%d,%d] graph_rows=%d reachable=%d",
144 len(needed_graph), _wcd_elapsed, _wcd_elapsed / max(len(needed_graph), 1),
145 min_have_gen, max_want_gen, len(graph_map), len(reachable_cids),
146 )
147 return needed_graph # type: ignore[return-value]
148
149 # Legacy fallback
150 from musehub.graph.walk import walk_dag_async
151
152 _row_cache: dict[str, MusehubCommit] = {}
153 _db_calls = 0
154
155 async def _adj(cid: str) -> list[str]:
156 nonlocal _db_calls
157 _db_calls += 1
158 row = await session.get(MusehubCommit, cid)
159 if row is not None:
160 _row_cache[cid] = row
161 return row.parent_ids or [] if row else []
162
163 needed_legacy: dict[str, MusehubCommit] = {}
164 async for cid in walk_dag_async(starts, _adj, exclude=have_set):
165 if cid in _row_cache:
166 needed_legacy[cid] = _row_cache[cid]
167
168 _wcd_elapsed = (_time_module.perf_counter() - _wcd_t0) * 1000
169 logger.info(
170 "[_walk_commit_delta] DONE (legacy) commits=%d db_calls=%d elapsed=%.1fms (%.2fms/commit)",
171 len(needed_legacy), _db_calls, _wcd_elapsed,
172 _wcd_elapsed / max(len(needed_legacy), 1),
173 )
174 return needed_legacy
175
176
177 async def wire_fetch_presign(
178 session: AsyncSession,
179 repo_id: str,
180 req: WireFetchRequest,
181 ttl_seconds: int = 3600,
182 ) -> FetchPresignResult:
183 import asyncio
184 from datetime import timedelta
185
186 _empty: FetchPresignResult = {
187 "presign": False,
188 "blob_urls": {},
189 "commits": [],
190 "snapshots": [],
191 "branch_heads": {},
192 "repo_id": repo_id,
193 "domain": "",
194 "default_branch": "main",
195 "expires_at": None,
196 "commit_count": 0,
197 "blob_count": 0,
198 }
199
200 if not req.want:
201 return _empty
202
203 repo_row = await session.get(MusehubRepo, repo_id)
204 if repo_row is None:
205 return _empty
206 _domain: str = repo_row.domain_id or ""
207 _default_branch: str = repo_row.default_branch if repo_row.default_branch else "main"
208 _empty["domain"] = _domain
209 _empty["default_branch"] = _default_branch
210 _empty["repo_id"] = repo_id
211
212 have_set = set(req.have)
213 needed_rows = await _walk_commit_delta(session, req.want, have_set)
214
215 if not needed_rows:
216 return {**_empty, "domain": _domain, "default_branch": _default_branch}
217
218 _presign_commit_rows: dict[str, MusehubCommit] = {}
219 _presign_any = next(iter(needed_rows.values()))
220 if not isinstance(_presign_any, MusehubCommit):
221 _PRESIGN_WIRE_BATCH = 2000
222 _presign_cids = list(needed_rows.keys())
223 for _pi in range(0, len(_presign_cids), _PRESIGN_WIRE_BATCH):
224 _pq = await session.execute(
225 select(MusehubCommit).where(MusehubCommit.commit_id.in_(_presign_cids[_pi : _pi + _PRESIGN_WIRE_BATCH]))
226 )
227 for _pr in _pq.scalars():
228 _presign_commit_rows[_pr.commit_id] = _pr
229 else:
230 _presign_commit_rows = needed_rows # type: ignore[assignment]
231
232 snap_ids = [r.snapshot_id for r in needed_rows.values() if r.snapshot_id]
233 all_oids: set[str] = set()
234 if snap_ids:
235 snaps_q = await session.execute(
236 select(MusehubSnapshot).where(MusehubSnapshot.snapshot_id.in_(snap_ids))
237 )
238 for snap in snaps_q.scalars().all():
239 manifest = (
240 _msgpack.unpackb(snap.manifest_blob, raw=False)
241 if snap.manifest_blob
242 else await _reconstruct_manifest(session, snap.snapshot_id)
243 )
244 all_oids.update(v for v in manifest.values() if v)
245
246 have_snap_ids: list[str] = []
247 if have_set:
248 have_commits_q = await session.execute(
249 select(MusehubCommit).where(MusehubCommit.commit_id.in_(have_set))
250 )
251 have_snap_ids = [r.snapshot_id for r in have_commits_q.scalars().all() if r.snapshot_id]
252 have_oids: set[str] = set()
253 if have_snap_ids:
254 have_snaps_q = await session.execute(
255 select(MusehubSnapshot).where(MusehubSnapshot.snapshot_id.in_(have_snap_ids))
256 )
257 for snap in have_snaps_q.scalars().all():
258 manifest = (
259 _msgpack.unpackb(snap.manifest_blob, raw=False)
260 if snap.manifest_blob
261 else await _reconstruct_manifest(session, snap.snapshot_id)
262 )
263 have_oids.update(v for v in manifest.values() if v)
264
265 new_oids = all_oids - have_oids
266 n_objects = len(new_oids)
267 n_commits = len(needed_rows)
268
269 total_size = 0
270 if new_oids:
271 size_q = await session.execute(
272 select(func.coalesce(func.sum(MusehubObject.size_bytes), 0)).where(
273 MusehubObject.object_id.in_(list(new_oids))
274 )
275 )
276 total_size = int(size_q.scalar() or 0)
277
278 wire_commits = [_to_wire_commit(row).model_dump() for row in _presign_commit_rows.values()]
279
280 snap_rows_q = await session.execute(
281 select(MusehubSnapshot).where(MusehubSnapshot.snapshot_id.in_(snap_ids))
282 )
283 wire_snaps = [_snap_row_to_wire(snap) for snap in snap_rows_q.scalars().all()]
284
285 branch_rows_q = await session.execute(
286 select(MusehubBranch).where(MusehubBranch.repo_id == repo_id)
287 )
288 branch_heads = {
289 b.name: b.head_commit_id
290 for b in branch_rows_q.scalars().all()
291 if b.head_commit_id
292 }
293
294 backend = get_backend()
295
296 sem = asyncio.Semaphore(50)
297
298 logger.info(
299 "fetch/presign: generating %d presigned GET URLs repo=%s/%s",
300 len(new_oids), repo_row.owner, repo_row.slug,
301 )
302
303 async def _presign_one(oid: str) -> tuple[str, str]:
304 async with sem:
305 url = await backend.presign_get(oid, ttl_seconds)
306 logger.debug("fetch/presign: presigned oid=%s", oid)
307 return oid, url
308
309 pairs = await asyncio.gather(*(_presign_one(oid) for oid in new_oids))
310 blob_urls = {oid: url for oid, url in pairs}
311 expires_at = (_utc_now() + timedelta(seconds=ttl_seconds)).isoformat()
312
313 return {
314 "presign": True,
315 "blob_urls": blob_urls,
316 "commits": wire_commits,
317 "snapshots": wire_snaps,
318 "branch_heads": branch_heads,
319 "repo_id": repo_id,
320 "domain": _domain,
321 "default_branch": _default_branch,
322 "expires_at": expires_at,
323 "commit_count": n_commits,
324 "blob_count": n_objects,
325 }
326
327 async def wire_fetch_mpack(
328 session: AsyncSession,
329 repo_id: str,
330 want: list[str],
331 have: list[str],
332 ttl_seconds: int = 3600,
333 ) -> FetchMPackResult:
334 import msgpack as _msgpack_local
335
336 _t0 = _time_module.perf_counter()
337 def _ms() -> float:
338 return (_time_module.perf_counter() - _t0) * 1000
339
340 logger.info("[wire_fetch_mpack] START repo_id=%s want=%d have=%d want_ids=%s",
341 repo_id, len(want), len(have), [cid[:16] for cid in want[:5]])
342
343 _up_to_date: FetchMPackResult = {
344 "mpack_url": None,
345 "mpack_id": None,
346 "commit_count": 0,
347 "blob_count": 0,
348 }
349
350 if not want:
351 logger.info("[wire_fetch_mpack] SKIP — want is empty")
352 return _up_to_date
353
354 have_set = set(have)
355 logger.info("[wire_fetch_mpack] step=1 DAG walk starting t=%.1fms", _ms())
356 needed_rows = await _walk_commit_delta(session, want, have_set)
357 logger.info("[wire_fetch_mpack] step=1 DAG walk done commits=%d t=%.1fms", len(needed_rows), _ms())
358
359 if not needed_rows:
360 logger.info("[wire_fetch_mpack] SKIP — client already up-to-date (needed_rows empty)")
361 return _up_to_date
362
363 commit_rows: dict[str, MusehubCommit] = {}
364 _any = next(iter(needed_rows.values()))
365 _is_proxy = not isinstance(_any, MusehubCommit)
366 logger.info("[wire_fetch_mpack] step=1b needed_rows=%d is_proxy=%s t=%.1fms",
367 len(needed_rows), _is_proxy, _ms())
368 if _is_proxy:
369 _cids = list(needed_rows.keys())
370 _q = await session.execute(
371 select(MusehubCommit).where(
372 _sa_text("commit_id = ANY(:ids)").bindparams(ids=_cids)
373 )
374 )
375 for _row in _q.scalars():
376 commit_rows[_row.commit_id] = _row
377 _missing_from_db = set(_cids) - set(commit_rows.keys())
378 logger.info(
379 "[wire_fetch_mpack] step=1b bulk fetch done commits_in_db=%d missing_from_db=%d "
380 "missing_ids=%s t=%.1fms",
381 len(commit_rows), len(_missing_from_db),
382 [cid[:16] for cid in list(_missing_from_db)[:5]], _ms(),
383 )
384 else:
385 commit_rows = needed_rows # type: ignore[assignment]
386 logger.info("[wire_fetch_mpack] step=1b using MusehubCommit rows directly commits=%d t=%.1fms",
387 len(commit_rows), _ms())
388
389 _proxy_snap_ids_raw = [r.snapshot_id for r in needed_rows.values()]
390 snap_ids = [sid for sid in _proxy_snap_ids_raw if sid]
391 _proxy_snap_none_count = sum(1 for s in _proxy_snap_ids_raw if not s)
392 _commit_row_snap_ids = [r.snapshot_id for r in commit_rows.values() if r.snapshot_id]
393 logger.info(
394 "[wire_fetch_mpack] step=2 snap_ids_from_graph=%d snap_ids_none_in_graph=%d "
395 "snap_ids_from_commit_rows=%d t=%.1fms",
396 len(snap_ids), _proxy_snap_none_count, len(_commit_row_snap_ids), _ms(),
397 )
398
399 snap_map: dict[str, dict] = {}
400 if snap_ids:
401 snaps_q = await session.execute(
402 select(MusehubSnapshot).where(
403 _sa_text("snapshot_id = ANY(:ids)").bindparams(ids=snap_ids)
404 )
405 )
406 for snap in snaps_q.scalars().all():
407 snap_map[snap.snapshot_id] = _snap_row_to_wire(snap)
408 logger.info("[wire_fetch_mpack] step=2 snap_map loaded=%d t=%.1fms", len(snap_map), _ms())
409
410 all_oids: set[str] = set()
411 _needed_cids = list(needed_rows.keys())
412 logger.warning("[GRAPH-DEBUG] wire_fetch_mpack: needed_rows=%d needed_cids_sample=%s",
413 len(_needed_cids), [c[:16] for c in _needed_cids[:3]])
414 _debug_graph_q = await session.execute(
415 select(MusehubCommitGraph.commit_id, MusehubCommitGraph.generation, MusehubCommitGraph.snapshot_id)
416 .where(MusehubCommitGraph.commit_id.in_(_needed_cids))
417 .order_by(MusehubCommitGraph.generation.desc())
418 .limit(5)
419 )
420 _debug_graph_rows = _debug_graph_q.all()
421 logger.warning("[GRAPH-DEBUG] wire_fetch_mpack: CommitGraph has %d rows for needed_cids (top 5 by gen): %s",
422 len(_debug_graph_rows),
423 [(r[1], r[0][:16]) for r in _debug_graph_rows])
424 want_tip_snap_q = await session.execute(
425 select(MusehubCommitGraph.snapshot_id)
426 .where(MusehubCommitGraph.commit_id.in_(_needed_cids))
427 .order_by(MusehubCommitGraph.generation.desc())
428 .limit(1)
429 )
430 want_tip_snap_id = want_tip_snap_q.scalar_one_or_none()
431 logger.warning("[GRAPH-DEBUG] wire_fetch_mpack: want_tip_snap_id=%s",
432 want_tip_snap_id[:20] if want_tip_snap_id else "NONE")
433 logger.info("[wire_fetch_mpack] step=2 want_tip_snap_id=%s (from CommitGraph) t=%.1fms",
434 want_tip_snap_id[:16] if want_tip_snap_id else None, _ms())
435 if want_tip_snap_id:
436 wt_blob_q = await session.execute(
437 select(MusehubSnapshot.manifest_blob)
438 .where(MusehubSnapshot.snapshot_id == want_tip_snap_id)
439 )
440 wt_blob = wt_blob_q.scalar_one_or_none()
441 if wt_blob:
442 all_oids.update(v for v in _msgpack_local.unpackb(wt_blob, raw=False).values() if v)
443 logger.warning("[GRAPH-DEBUG] wire_fetch_mpack: want_tip manifest all_oids=%d wt_blob_present=%s",
444 len(all_oids), wt_blob is not None)
445 logger.info("[wire_fetch_mpack] step=2 want_tip manifest all_oids=%d wt_blob_present=%s t=%.1fms",
446 len(all_oids), wt_blob is not None, _ms())
447 else:
448 logger.warning(
449 "[wire_fetch_mpack] step=2 WARN want_tip_snap_id=None — CommitGraph missing tip "
450 "needed_cids=%s commit_rows_snap_ids=%s",
451 [cid[:16] for cid in list(needed_rows.keys())[:5]],
452 [sid[:16] for sid in _commit_row_snap_ids[:5]],
453 )
454
455 have_oids: set[str] = set()
456 if have_set:
457 ht_snap_q = await session.execute(
458 select(MusehubCommitGraph.snapshot_id)
459 .where(MusehubCommitGraph.commit_id.in_(list(have_set)))
460 .order_by(MusehubCommitGraph.generation.desc())
461 .limit(1)
462 )
463 have_tip_snap_id = ht_snap_q.scalar_one_or_none()
464 if have_tip_snap_id:
465 ht_blob_q = await session.execute(
466 select(MusehubSnapshot.manifest_blob)
467 .where(MusehubSnapshot.snapshot_id == have_tip_snap_id)
468 )
469 ht_blob = ht_blob_q.scalar_one_or_none()
470 if ht_blob:
471 have_oids.update(v for v in _msgpack_local.unpackb(ht_blob, raw=False).values() if v)
472
473 new_oids = all_oids - have_oids
474 logger.info(
475 "[wire_fetch_mpack] step=2 done snap_map=%d all_oids=%d have_oids=%d new_oids=%d t=%.1fms",
476 len(snap_map), len(all_oids), len(have_oids), len(new_oids), _ms(),
477 )
478
479 if new_oids:
480 indexed_q = await session.execute(
481 select(MusehubMPackIndex.entity_id)
482 .where(MusehubMPackIndex.entity_id.in_(list(new_oids)))
483 .where(MusehubMPackIndex.entity_type == "object")
484 )
485 indexed_oids = {row[0] for row in indexed_q}
486 missing = new_oids - indexed_oids
487 if missing:
488 logger.warning(
489 "[wire_fetch_mpack] step=3 NOT INDEXED %d/%d objects — raising FetchNotIndexedError t=%.1fms",
490 len(missing), len(new_oids), _ms(),
491 )
492 raise FetchNotIndexedError(len(missing))
493 logger.info("[wire_fetch_mpack] step=3 index coverage OK oids=%d t=%.1fms", len(new_oids), _ms())
494
495 backend = get_backend()
496
497 cache_hits: dict[str, bytes] = {}
498 if new_oids:
499 _CACHE_CHUNK = 10000
500 _new_oid_list = list(new_oids)
501 for _ci in range(0, len(_new_oid_list), _CACHE_CHUNK):
502 _chunk = _new_oid_list[_ci : _ci + _CACHE_CHUNK]
503 _cache_q = await session.execute(
504 select(MusehubObject.object_id, MusehubObject.content_cache)
505 .where(MusehubObject.object_id.in_(_chunk))
506 .where(MusehubObject.content_cache.isnot(None))
507 )
508 for _oid, _cached in _cache_q:
509 if _cached:
510 cache_hits[_oid] = bytes(_cached)
511
512 cache_miss_oids = [oid for oid in new_oids if oid not in cache_hits]
513
514 oid_to_mpack: dict[str, str] = {}
515 if cache_miss_oids:
516 _MIDX_CHUNK = 10000
517 for _ci in range(0, len(cache_miss_oids), _MIDX_CHUNK):
518 _chunk = cache_miss_oids[_ci : _ci + _MIDX_CHUNK]
519 _midx_q = await session.execute(
520 select(MusehubMPackIndex.entity_id, MusehubMPackIndex.mpack_id)
521 .where(MusehubMPackIndex.entity_id.in_(_chunk))
522 .where(MusehubMPackIndex.entity_type == "object")
523 )
524 for _oid, _mid in _midx_q:
525 oid_to_mpack[_oid] = _mid
526
527 mpack_to_oids: dict[str, list[str]] = {}
528 no_mpack_oids: list[str] = []
529 for oid in cache_miss_oids:
530 mid = oid_to_mpack.get(oid)
531 if mid:
532 mpack_to_oids.setdefault(mid, []).append(oid)
533 else:
534 no_mpack_oids.append(oid)
535
536 mpack_hits: dict[str, bytes] = {}
537 mpack_miss_oids: list[str] = []
538 _sem_mpack = asyncio.Semaphore(8)
539
540 async def _extract_from_mpack(mpack_id: str, oids: list[str]) -> None:
541 async with _sem_mpack:
542 raw = await backend.get_mpack(mpack_id)
543 if raw is None:
544 mpack_miss_oids.extend(oids)
545 return
546 import zstandard as _zstd_phase1
547 _dctx_phase1 = _zstd_phase1.ZstdDecompressor()
548 try:
549 if raw[:4] == b"MUSE":
550 from muse.core.mpack import parse_wire_mpack as _parse_wire_fetch
551 payload = _parse_wire_fetch(raw)
552 else:
553 payload = _msgpack_local.unpackb(raw, raw=False)
554 except Exception as _parse_err:
555 logger.warning(
556 "[_extract_from_mpack] failed to parse mpack=%s: %s",
557 mpack_id[:20], _parse_err,
558 )
559 mpack_miss_oids.extend(oids)
560 return
561 obj_index: dict[str, bytes] = {}
562 for o in payload.get("blobs", []):
563 oid_entry = o.get("object_id", "")
564 content = o.get("content") or b""
565 if not isinstance(content, bytes):
566 content = bytes(content)
567 _ZSTD_MAGIC = b"\x28\xb5\x2f\xfd"
568 if (o.get("encoding") == "zstd" or content[:4] == _ZSTD_MAGIC) and content:
569 try:
570 content = _dctx_phase1.decompress(content)
571 except Exception as _decomp_err:
572 logger.warning(
573 "[_extract_from_mpack] zstd decompress failed oid=%s: %s",
574 oid_entry[:20], _decomp_err,
575 )
576 continue
577 obj_index[oid_entry] = content
578 for oid in oids:
579 content = obj_index.get(oid)
580 if content is not None:
581 mpack_hits[oid] = content
582 else:
583 mpack_miss_oids.append(oid)
584
585 if mpack_to_oids:
586 await asyncio.gather(
587 *(_extract_from_mpack(mid, oids) for mid, oids in mpack_to_oids.items())
588 )
589
590 legacy_hits: dict[str, bytes] = {}
591 _fallback_oids = no_mpack_oids + mpack_miss_oids
592 if _fallback_oids:
593 _sem_legacy = asyncio.Semaphore(50)
594
595 async def _get_legacy(oid: str) -> None:
596 async with _sem_legacy:
597 data = await backend.get(oid)
598 if data:
599 legacy_hits[oid] = data
600
601 await asyncio.gather(*(_get_legacy(oid) for oid in _fallback_oids))
602
603 _all_blob_bytes: dict[str, bytes] = {**legacy_hits, **mpack_hits, **cache_hits}
604 blob_pairs = [(oid, _all_blob_bytes[oid]) for oid in new_oids if oid in _all_blob_bytes]
605 logger.info(
606 "[wire_fetch_mpack] step=4 fetched %d blobs (cache=%d mpack=%d legacy=%d) t=%.1fms",
607 len(blob_pairs), len(cache_hits), len(mpack_hits), len(legacy_hits), _ms(),
608 )
609
610 wire_commits = [_to_wire_commit(row).model_dump() for row in commit_rows.values()]
611 wire_snaps = [snap_map[sid] for sid in snap_ids if sid in snap_map]
612 wire_blobs = [
613 {"object_id": oid, "content": data}
614 for oid, data in blob_pairs
615 if data
616 ]
617 logger.info(
618 "[wire_fetch_mpack] step=5 assembly: wire_commits=%d wire_snaps=%d wire_blobs=%d "
619 "snap_ids_total=%d snap_ids_in_map=%d commit_rows=%d t=%.1fms",
620 len(wire_commits), len(wire_snaps), len(wire_blobs),
621 len(snap_ids), sum(1 for sid in snap_ids if sid in snap_map),
622 len(commit_rows), _ms(),
623 )
624
625 from muse.core.mpack import build_wire_mpack as _build_wire_mpack
626 _head_commit_id = want[0] if want else ""
627 mpack_bytes = _build_wire_mpack(
628 {
629 "commits": wire_commits,
630 "snapshots": wire_snaps,
631 "blobs": wire_blobs,
632 "tags": [],
633 },
634 meta={"repo_id": repo_id, "head_commit_id": _head_commit_id},
635 )
636 mpack_id = blob_id(mpack_bytes)
637
638 n_commits = len(wire_commits)
639 n_blobs = len(wire_blobs)
640 logger.info(
641 "[wire_fetch_mpack] step=5 assembled commits=%d snapshots=%d blobs=%d bytes=%d t=%.1fms",
642 n_commits, len(wire_snaps), n_blobs, len(mpack_bytes), _ms(),
643 )
644
645 await backend.put_mpack(mpack_id, mpack_bytes)
646 mpack_url = await backend.presign_mpack_get(mpack_id, ttl_seconds)
647 logger.info(
648 "[wire_fetch_mpack] step=6 mpack_id=%s mpack_url=%s t=%.1fms",
649 mpack_id[:20], mpack_url[:80] if mpack_url else None, _ms(),
650 )
651 logger.info("[wire_fetch_mpack] RETURN commits=%d blobs=%d TOTAL=%.1fms", n_commits, n_blobs, _ms())
652
653 async def _cleanup() -> None:
654 await asyncio.sleep(ttl_seconds)
655 try:
656 await backend.delete(mpack_id)
657 except Exception:
658 pass
659
660 asyncio.ensure_future(_cleanup())
661
662 return {
663 "mpack_url": mpack_url,
664 "mpack_id": mpack_id,
665 "commit_count": n_commits,
666 "blob_count": n_blobs,
667 }
668
669 async def _check_missing_objects(
670 session: AsyncSession,
671 needs_check: set[str],
672 ) -> set[str]:
673 if not needs_check:
674 return set()
675 from musehub.db.musehub_repo_models import MusehubObject
676 registered: set[str] = set(
677 (await session.execute(
678 select(MusehubObject.object_id).where(
679 MusehubObject.object_id.in_(list(needs_check)),
680 MusehubObject.deleted_at.is_(None),
681 )
682 )).scalars().all()
683 )
684 return needs_check - registered
685
686
687 class MPackGCResult(TypedDict):
688 skipped: bool
689 packs_before: int
690 packs_after: int
691 consolidated_key: str
692
693
694 async def process_mpack_gc_job(session: AsyncSession, repo_id: str) -> MPackGCResult:
695 import msgpack as _mp
696
697 _skipped: MPackGCResult = {
698 "skipped": True,
699 "packs_before": 0,
700 "packs_after": 0,
701 "consolidated_key": "",
702 }
703
704 repo_oids_q = await session.execute(
705 select(MusehubObjectRef.object_id)
706 .where(MusehubObjectRef.repo_id == repo_id)
707 )
708 repo_oid_set = {row[0] for row in repo_oids_q}
709 mpack_q = await session.execute(
710 select(MusehubMPackIndex.mpack_id)
711 .where(MusehubMPackIndex.entity_id.in_(list(repo_oid_set)))
712 .where(MusehubMPackIndex.entity_type == "object")
713 .distinct()
714 )
715 mpack_ids = [row[0] for row in mpack_q]
716 packs_before = len(mpack_ids)
717
718 if packs_before <= 1:
719 _skipped["packs_before"] = packs_before
720 if mpack_ids:
721 _skipped["consolidated_key"] = mpack_ids[0]
722 return _skipped
723
724 import musehub.storage.backends as _backends_mod
725 backend = _backends_mod.get_backend()
726
727 merged_objects: dict[str, bytes] = {}
728
729 async def _download(pid: str) -> None:
730 raw = await backend.get_mpack(pid)
731 if not raw:
732 logger.warning("[mpack_gc] mpack not found in storage: %s", pid)
733 return
734 if raw[:4] == b"MUSE":
735 from muse.core.mpack import parse_wire_mpack as _parse_gc
736 _parsed = _parse_gc(raw)
737 else:
738 _parsed = _mp.unpackb(raw, raw=False)
739 for obj in _parsed.get("blobs", []):
740 oid = obj.get("object_id", "")
741 content = obj.get("content", b"")
742 if oid and oid not in merged_objects:
743 merged_objects[oid] = content
744
745 await asyncio.gather(*(_download(pid) for pid in mpack_ids))
746
747 from muse.core.mpack import build_wire_mpack as _build_gc_mpack
748 consolidated_bytes = _build_gc_mpack({
749 "commits": [],
750 "snapshots": [],
751 "blobs": [
752 {"object_id": oid, "content": merged_objects[oid]}
753 for oid in sorted(merged_objects)
754 ],
755 "tags": [],
756 })
757 consolidated_key = "sha256:" + hashlib.sha256(consolidated_bytes).hexdigest()
758
759 await backend.put_mpack(consolidated_key, consolidated_bytes)
760
761 old_mpack_ids = [p for p in mpack_ids if p != consolidated_key]
762 if old_mpack_ids:
763 from sqlalchemy import delete as sa_delete
764 await session.execute(
765 sa_delete(MusehubMPackIndex)
766 .where(MusehubMPackIndex.mpack_id.in_(old_mpack_ids))
767 .where(MusehubMPackIndex.entity_type == "object")
768 )
769 _gc_now = datetime.now(timezone.utc)
770 new_rows = [
771 {
772 "entity_id": oid,
773 "mpack_id": consolidated_key,
774 "entity_type": "object",
775 "created_at": _gc_now,
776 }
777 for oid in merged_objects
778 ]
779 if new_rows:
780 _GC_MIDX_CHUNK = 5000
781 for _gmi in range(0, len(new_rows), _GC_MIDX_CHUNK):
782 await session.execute(
783 _pg_insert(MusehubMPackIndex)
784 .values(new_rows[_gmi : _gmi + _GC_MIDX_CHUNK])
785 .on_conflict_do_nothing(index_elements=["entity_id", "mpack_id"])
786 )
787
788 logger.info(
789 "[mpack_gc] repo=%s consolidated %d mpacks → 1 (objects=%d key=%s)",
790 repo_id, packs_before, len(merged_objects), consolidated_key,
791 )
792
793 return {
794 "skipped": False,
795 "packs_before": packs_before,
796 "packs_after": 1,
797 "consolidated_key": consolidated_key,
798 }
799
800
801 class FetchResult(TypedDict):
802 mpack_id: str
803 mpack_url: str | None
804 commit_count: int
805 blob_count: int
806
807
808 class FetchCommitNotFound(Exception):
809 """A want commit_id does not exist in musehub_commits."""
810
811
812 class FetchNotReady(Exception):
813 """Needed objects are absent from musehub_mpack_index — client must retry."""
814
815
816 async def wire_fetch(
817 session: AsyncSession,
818 repo_id: str,
819 want: list[str],
820 have: list[str],
821 ttl_seconds: int = 3600,
822 ) -> FetchResult:
823 import msgpack as _mp
824
825 _empty: FetchResult = {"mpack_id": "", "mpack_url": None, "commit_count": 0, "blob_count": 0}
826
827 for entry in want:
828 if not (isinstance(entry, str) and entry.startswith("sha256:")):
829 raise MPackValidationError(f"want entry is not a sha256: id: {entry!r}")
830
831 for entry in have:
832 if not (isinstance(entry, str) and entry.startswith("sha256:")):
833 raise MPackValidationError(f"have entry is not a sha256: id: {entry!r}")
834
835 if want:
836 existing_q = await session.execute(
837 select(MusehubCommit.commit_id).where(MusehubCommit.commit_id.in_(want))
838 )
839 found = {row[0] for row in existing_q}
840 missing_want = [cid for cid in want if cid not in found]
841 if missing_want:
842 raise FetchCommitNotFound(missing_want[0])
843
844 have_set = set(have)
845 needed = await _walk_commit_delta(session, want, have_set)
846 if not needed:
847 return _empty
848
849 cids = list(needed.keys())
850 commit_rows: dict[str, MusehubCommit] = {}
851 for i in range(0, len(cids), 2000):
852 q = await session.execute(
853 select(MusehubCommit).where(MusehubCommit.commit_id.in_(cids[i:i + 2000]))
854 )
855 for row in q.scalars():
856 commit_rows[row.commit_id] = row
857
858 want_snap_ids = {r.snapshot_id for r in needed.values() if r.snapshot_id}
859 have_snap_ids: set[str] = set()
860 if have_set:
861 have_commits_q = await session.execute(
862 select(MusehubCommit.snapshot_id).where(MusehubCommit.commit_id.in_(list(have_set)))
863 )
864 have_snap_ids = {row[0] for row in have_commits_q if row[0]}
865
866 new_snap_ids = want_snap_ids - have_snap_ids
867 snap_map: dict[str, dict] = {}
868 new_oids: set[str] = set()
869 if new_snap_ids:
870 snaps_q = await session.execute(
871 select(MusehubSnapshot).where(MusehubSnapshot.snapshot_id.in_(list(new_snap_ids)))
872 )
873 for snap in snaps_q.scalars():
874 manifest = (
875 _mp.unpackb(snap.manifest_blob, raw=False)
876 if snap.manifest_blob
877 else await _reconstruct_manifest(session, snap.snapshot_id)
878 )
879 new_oids.update(v for v in manifest.values() if v)
880 snap_map[snap.snapshot_id] = _snap_row_to_wire(snap)
881
882 if have_snap_ids:
883 have_snaps_q = await session.execute(
884 select(MusehubSnapshot).where(MusehubSnapshot.snapshot_id.in_(list(have_snap_ids)))
885 )
886 for snap in have_snaps_q.scalars():
887 m = (
888 _mp.unpackb(snap.manifest_blob, raw=False)
889 if snap.manifest_blob
890 else await _reconstruct_manifest(session, snap.snapshot_id)
891 )
892 new_oids -= {v for v in m.values() if v}
893
894 if new_oids:
895 idx_q = await session.execute(
896 select(MusehubMPackIndex.entity_id).where(
897 MusehubMPackIndex.entity_id.in_(list(new_oids)),
898 MusehubMPackIndex.entity_type == "object",
899 )
900 )
901 indexed = {row[0] for row in idx_q}
902 unindexed = new_oids - indexed
903 if unindexed:
904 raise FetchNotReady(f"{len(unindexed)} object(s) not yet in mpack_index")
905
906 backend = get_backend()
907 objects: list[dict] = []
908 if new_oids:
909 obj_q = await session.execute(
910 select(MusehubObject).where(MusehubObject.object_id.in_(list(new_oids)))
911 )
912 for obj_row in obj_q.scalars():
913 if obj_row.content_cache is not None:
914 content = obj_row.content_cache
915 else:
916 content = await backend.get(obj_row.object_id) or b""
917 objects.append({"object_id": obj_row.object_id, "content": content})
918
919 wire_commits = [_to_wire_commit(r).model_dump() for r in commit_rows.values()]
920 from muse.core.mpack import build_wire_mpack as _build_fetch_mpack
921 wire_bytes = _build_fetch_mpack({
922 "commits": wire_commits,
923 "snapshots": list(snap_map.values()),
924 "blobs": objects,
925 "tags": [],
926 })
927 mpack_id = blob_id(wire_bytes)
928
929 await backend.put_mpack(mpack_id, wire_bytes)
930 mpack_url = await backend.presign_mpack_get(mpack_id, ttl_seconds)
931
932 return {
933 "mpack_id": mpack_id,
934 "mpack_url": mpack_url,
935 "commit_count": len(commit_rows),
936 "blob_count": len(objects),
937 }
File History 1 commit
sha256:f99af7b1a7f36c4d537d1c630d4b71fc39222b1255f82e930929e2fc89015e11 fix: relax browse_repo perf budget to 500ms — 200ms was too… Sonnet 4.6 99 days ago