Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
0.5.32: reduce organization history and inventory costs
Browse filesUse adaptive history pages, compact inventories and indexed identity updates. Preserve cursors, counts, privacy and API pacing. Real 90-organization comparison: 1101 to 473 requests, identical 40187 events. 576 Python tests, six Node suites, desktop/mobile and public bucket round-trip verified.
Files changed (12)
- CHANGELOG.md+7
- ORGANIZATION_PERFORMANCE.mdAdded+97
- PUBLIC_CACHE.md+6
- README.md+7-1
- VALIDATION.md+13-1
- contrib/aggregation.py+14-2
- contrib/collectors/organizations.py+45-5
- contrib/config.py+1-1
- releases/HF-Contrib-v2-0.5.32.zipAdded+3
- tests/benchmark_organization_scaling.pyAdded+16
- tests/benchmark_organization_scan.pyAdded+100
- tests/test_organization_performance.pyAdded+116
12345# Changelog## 0.5.31 — personal result first, optional organizations- Make organization repository scanning a separate Add/Continue/Refresh action after the personal result. Keep public cross-Hub community events in the personal scan.123456789101112# Changelog## 0.5.32 — reduce organization request and indexing costs- Use adaptive 100 → 1,000 commit pages for deep organization histories, with overlapping head reads, exact deduplication and unchanged legacy cursors. Keep small/unchanged heads small.- Request compact inventory metadata; use fresh explicit public zero counts to avoid empty kind inventories. Unknown/invalid/refused hints fall back, and private scans always read their authenticated inventories.- Index stable repository IDs and affected commit events rather than repeatedly scanning every repository/event. Preserve transfers, independent forks, visibility and identity enrichment.- Keep the organization action optional, with existing API rates, Stop/resume, private checkpoints and aggregate-only public publication. No dependency, OAuth, source-version or schema changes.## 0.5.31 — personal result first, optional organizations- Make organization repository scanning a separate Add/Continue/Refresh action after the personal result. Keep public cross-Hub community events in the personal scan.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697# Organization scan performance · 0.5.32
The optional organization extension still reads available histories and attributescommits only to linked Hub authors matching the scanned profile. It does not inferauthorship from membership or the repository owner. The personal result staysusable before the extension is requested.
## What was expensive
- Deep histories: on the Julien 2026 reference, two datasets alone required 528 of the original 832 history requests, despite producing few matching commits. The documented Hub commit endpoint has no author filter.- Every inventory row searched all previously seen repositories twice by stable ID. Metadata updates also walked the entire contribution ledger. Both costs grew unnecessarily with large organizations and personal histories.- Full repository metadata and three inventories for empty namespaces added transfer and request overhead.
## Changes
1. Read the first 100 commits, then use 1,000-record pages only when relevant history remains. Restart the wider first page with overlap and exact event deduplication. A returned or saved cursor retains its original page size; existing checkpoints never reinterpret an offset with a different limit.2. Request only stable identity, revision, visibility, creation/modification dates and, where supported, gating status. Spaces do not request the model/dataset `gated` expansion. The Hub returns `id` and `_id` without an explicit expansion.3. Use transient indexes for stable repository IDs and affected commit events. Renames/transfers still enrich identities; independent forks and recreated paths remain distinct. Legacy aliases retain their compatibility path.4. For public full-namespace discovery, accept only fresh, explicit integer zero counts from the matching organization overview to skip empty kind inventories. Unknown, malformed or refused responses fall back to normal listings. Pending inventory work is retained. Hints expire with the action and are not stored. Private scans always read authenticated inventories, regardless of public zeros.
Existing request pacing, cooldowns, concurrency, automatic continuation, Stop andresume remain unchanged. No dependency, OAuth, source-version or schema change.Private checkpoints keep the complete event ledger and exact cursors. Publicpublication still verifies current visibility and exposes aggregates only. Noproduction profile mirror or private checkpoint needs migration.
## Real anonymous comparison, 28 November 2026
Same HF CPU Job, same saved public personal base, organization extension only,0.5.31 versus 0.5.32. Each cold run starts without organization state; each Refreshreuses its own resulting checkpoint. Checkpoints are validated and saved locally;times exclude production bucket uploads. These are individual measurements, notan SLA or a measurement of a newly scanned complete personal year.
| Measure | 0.5.31 | 0.5.32 || --- | ---: | ---: || Organization traversal | 162.49 s | 113.78 s || Organization Refresh | 37.33 s | 29.85 s || History requests, initial traversal | 832 | 248 || Inventory requests, initial traversal | 208 | 95 || Metadata requests, initial traversal | 61 | 130 || Total measured requests, initial traversal | 1,101 | 473 || Total measured requests, Refresh | 244 | 188 || Organizations checked | 90 | 90 || Repositories read | 846 | 846 || Attributed organization commits | 20 | 20 || Full raw contributions, including saved personal base | 40,187 | 40,187 |
The complete serialized event sets and repository sets match exactly, as do dailybins and automation aggregates. No HTTP 429 was observed. Two gated historiesremain inaccessible (401) in both runs and are reported partial. Old personalwarnings in the shared base were not rescanned or claimed fixed by this comparison.
The initial extension is about 30% shorter in this measurement, with 57% fewertotal measured requests. It can still take minutes for large namespaces: withoutan author-filtered Hub history endpoint, unrelated commits must be examined toestablish which ones belong to the profile. This is why the extension remains optional.
A separate synthetic 5,000-repository inventory benchmark, with histories outsidethe year, reduces Python CPU time from 7.14 to 0.15 seconds cold and 12.77 to 0.32seconds on Refresh. This isolates local indexing work; it is not a real networkscan timing.
## Reproduce
```shpython -m pytest -q tests/test_organization_performance.py tests/test_organizations.pypython tests/benchmark_organization_scaling.py 5000python tests/benchmark_organization_scan.py --base /path/to/public-checkpoint.json.gz --output dist/organization-run```
The real benchmark accepts an existing public-only full checkpoint, performsanonymous requests, and writes only into the new local output directory. It doesnot read or publish buckets. Use `--source-root /path/to/baseline` for the baselineand a different output directory, then compare full `events` sets from bothcompressed checkpoints. Keep these local ledgers out of release archives.
The Hub maximum `limit=1000` and supported inventory `expand` values were checkedagainst the official [Hub OpenAPI specification](https://huggingface.co/.well-known/openapi.json)and exercised against the live anonymous endpoints. The organization overviewoptimization has a conservative fallback because its hints are not the event source.47 unmodified lines48495051525347 unmodified lines## Publication boundary- Recompute counts from the complete server ledger. Exclude every event marked private, and every repository event whose repository is not explicitly known to be public in the current listing. A repository that became private or disappeared is not assumed public from an old checkpoint.- Normal scans reuse their repository discovery result. If that listing was skipped/incomplete, anonymous discovery checks visibility before publication. A failed verification/upload preserves the previous public copy and the independent personal backup; the UI reports the public-copy failure.- Only allowlisted fields above may be uploaded. No OAuth token, stable account ID, private count, repository name, commit ID, event title/body/URL, diagnostic, issue, private source error or raw checkpoint is published.47 unmodified lines48495051525354555657585947 unmodified lines## Publication boundaryOrganization performance changes in 0.5.32 do not alter the public format or storedledger. Identity indexes and fresh zero-count inventory hints remain in memoryonly. Public zeros never establish private coverage or replace a fresh repositoryvisibility check at publication. Larger commit pages retain exact deduplication,and existing saved cursors keep their original size. No bucket migration is needed.- Recompute counts from the complete server ledger. Exclude every event marked private, and every repository event whose repository is not explicitly known to be public in the current listing. A repository that became private or disappeared is not assumed public from an old checkpoint.- Normal scans reuse their repository discovery result. If that listing was skipped/incomplete, anonymous discovery checks visibility before publication. A failed verification/upload preserves the previous public copy and the independent personal backup; the UI reports the public-copy failure.- Only allowlisted fields above may be uploaded. No OAuth token, stable account ID, private count, repository name, commit ID, event title/body/URL, diagnostic, issue, private source error or raw checkpoint is published.
15 unmodified lines161718192021225 unmodified lines28293031323315 unmodified linesshort_description: Your Hugging Face activity, by day and contribution type.---# HF Contrib · 0.5.31A contribution explorer for your own Hugging Face account. Signed-out visitors have one sign-in button in the welcome screen; the header account action appears only after authentication, for signing out. The server selects the signed-in account. The Space maintainer can also inspect the public activity of another profile. One annual calendar changes with the selected activity family. The annual calendar shows incoming activity as it is collected. Repository stars lead, followed by timeline stars. Repository batches reveal dates in calendar order; live timeline batches interlace two chronological halves of the dates already received. Choose English or French and a light, dark or system theme. Select a day for its contribution breakdown, timestamps, titles and direct Hub links. Completed results can be exported as an overview PNG with all twelve activity categories.5 unmodified linesThe Publications view includes Daily Papers submissions, authored research papers, published blog articles and social posts. Posts and blog articles share the publication family’s cyan palette and triangular pending marker. Post replies appear in Community with turquoise diamonds; emoji reactions appear in Reactions with coral circles. Export height follows the twelve categories: 2800 × 4032 px, plus 44 px for the automation explanation and 64 px when the featured annual count is present.## Optional organization collection (0.5.31)The first scan and ordinary **Refresh** collect personal repositories, public feeds across the Hub and, when requested, private discussions in the personal namespace. Organization repository enumeration/history is a separate **Add organization activity** action below Replay/Options. This extension includes strictly attributed commits and, with private activity enabled, your own private organization discussions. It automatically continues bounded passes and retains Stop/resume. Existing organization events, resume positions and featured metadata survive a personal Refresh or full personal rescan.15 unmodified lines161718192021225 unmodified lines28293031323334353637383915 unmodified linesshort_description: Your Hugging Face activity, by day and contribution type.---# HF Contrib · 0.5.32A contribution explorer for your own Hugging Face account. Signed-out visitors have one sign-in button in the welcome screen; the header account action appears only after authentication, for signing out. The server selects the signed-in account. The Space maintainer can also inspect the public activity of another profile. One annual calendar changes with the selected activity family. The annual calendar shows incoming activity as it is collected. Repository stars lead, followed by timeline stars. Repository batches reveal dates in calendar order; live timeline batches interlace two chronological halves of the dates already received. Choose English or French and a light, dark or system theme. Select a day for its contribution breakdown, timestamps, titles and direct Hub links. Completed results can be exported as an overview PNG with all twelve activity categories.5 unmodified linesThe Publications view includes Daily Papers submissions, authored research papers, published blog articles and social posts. Posts and blog articles share the publication family’s cyan palette and triangular pending marker. Post replies appear in Community with turquoise diamonds; emoji reactions appear in Reactions with coral circles. Export height follows the twelve categories: 2800 × 4032 px, plus 44 px for the automation explanation and 64 px when the featured annual count is present.## Organization scan optimization (0.5.32)Organization histories now start with a small 100-commit head check and widen to 1,000 only when more history is needed. The widening overlaps the head; existing deduplication preserves every event and saved/server cursors keep their original page size. Inventories request only stable IDs, revision, visibility and dates, plus gated status for models/datasets.Stable repository and event indexes replace repeated whole-inventory/ledger searches. Fresh explicit zero counts on a public organization overview avoid empty kind listings; missing, invalid or refused hints fall back to ordinary discovery. These hints never certify private inventories and do not persist across scans. Existing request rates, attribution, cancellation, optional organization action, checkpoint formats and public/private separation remain unchanged. See [ORGANIZATION_PERFORMANCE.md](ORGANIZATION_PERFORMANCE.md) for measured results and remaining costs.## Optional organization collection (0.5.31)The first scan and ordinary **Refresh** collect personal repositories, public feeds across the Hub and, when requested, private discussions in the personal namespace. Organization repository enumeration/history is a separate **Add organization activity** action below Replay/Options. This extension includes strictly attributed commits and, with private activity enabled, your own private organization discussions. It automatically continues bounded passes and retains Stop/resume. Existing organization events, resume positions and featured metadata survive a personal Refresh or full personal rescan.
1234# Release validation · 0.5.30## v0.5.31 — optional organization extension12345678910111213141516# Release validation · 0.5.32## v0.5.32 — organization request and indexing costsBase: `b44842f72880fb360107e1c53ff0a786503210b7` (0.5.31), verified as repository and RUNNING runtime before editing. Reproduction and limits: [ORGANIZATION_PERFORMANCE.md](ORGANIZATION_PERFORMANCE.md).- **576 Python tests pass locally and in the HF CPU Job; six Node suites pass.** New regressions cover adaptive large pages, legacy cursors, overlap/deduplication across automatic continuation, compact inventories, recreated paths, indexed identity changes and public zero hints with private/malformed-count fallbacks. Existing cancellation, transfer/fork attribution, private coverage, aggregation, featured and automation regressions remain green.- **Real anonymous organization extension, same saved public Julien 2026 base:** 162.49 → 113.78 s cold; 37.33 → 29.85 s Refresh. Total measured cold requests 1,101 → 473; history 832 → 248; inventory 208 → 95. Exact equality of 40,187 serialized events, 846 repository identities and daily/automation aggregates; 20 attributed organization commits, 90/90 organizations checked. No 429 observed. Two gated histories remain partial in both versions. These timings use validated local checkpoints and exclude production uploads; this is not a fresh personal annual scan.- **Synthetic 5,000-repository CPU benchmark:** 7.14 → 0.15 s cold and 12.77 → 0.32 s Refresh in the same HF Job. This isolates inventory/indexing work without real network traffic.- **Actual Gradio/Chromium with synthetic OAuth/Hub/buckets:** 1200 px EN/light and 390 px FR/dark pass personal → public extension → personal private → private extension → cold restore → personal Refresh, with exact 241 → 243 → 243 → 250 counts. Mobile Stop/resume, optional source state, button bounds, no horizontal overflow and no browser errors pass. No UI assets changed.- **Real public bucket round-trip:** fresh anonymous repository-visibility projection of 40,187 raw public contributions including 20 organization commits; temporary object write, exact anonymous read and verified deletion. Existing profile/year mirrors and private backups remain untouched. Complete private bucket lifecycle remains simulated.- No dependency, OAuth, schema, source-version or intensity-policy change. In-memory indexes and zero hints are not persisted. Existing checkpoints remain readable and exact saved pagination is retained. No migration/rescan required; existing deep cursors retain their old size until a new head traversal.- No new real OAuth login, complete real private annual scan or physical Safari test is claimed. The previously noted WebKit ResizeObserver warning is outside this change. Publication checks the exact RUNNING commit, served config/assets and complete anonymous source archive.## v0.5.31 — optional organization extension
31 unmodified lines32333435363781 unmodified lines11912012112212312455 unmodified lines18018118218318418574 unmodified lines26026126226326426526626731 unmodified linesself.seen = set()self.events = {}self.commit_observations = {}self.ambiguous_organization_repos = set()self.space_creation_days = {}self.detail_counts = {}81 unmodified linesself.events[identity] = eventif event.key.endswith('.commit'):self.commit_observations.setdefault((event.key,event.identity.rsplit(':',1)[-1]),set()).add(identity)self.automation.update(event)if event.organization:self.organization_automation.update(event)55 unmodified linescommit=(previous.key,previous.identity.rsplit(':',1)[-1])self.commit_observations[commit].discard(identity)if not self.commit_observations[commit]:del self.commit_observations[commit]self.automation.update(None, previous)(self.organization_automation if previous.organization else self.personal_automation).update(None, previous)74 unmodified lines# A verified stable Hub ID keeps renamed histories linked.# Original personal attribution remains unchanged on transfer.by_uid = {(k.partition(':')[0],r.get('uid')):r for k,r in changed.items() if r.get('uid')}for event in list(self.events.values()):if not event.key.endswith('.commit'): continuekind = event.key.partition('.')[0]row = by_uid.get((kind,event.repo_uid)) or aliases.get(kind + ':' + event.repo)if row and row.get('repo'):31 unmodified lines3233343536373881 unmodified lines12012112212312412512612755 unmodified lines18318418518618718818919019119274 unmodified lines26726826927027127227327427527627727827931 unmodified linesself.seen = set()self.events = {}self.commit_observations = {}self.commits_by_repo_uid = {}self.ambiguous_organization_repos = set()self.space_creation_days = {}self.detail_counts = {}81 unmodified linesself.events[identity] = eventif event.key.endswith('.commit'):self.commit_observations.setdefault((event.key,event.identity.rsplit(':',1)[-1]),set()).add(identity)if event.repo_uid:self.commits_by_repo_uid.setdefault((event.key.partition('.')[0],event.repo_uid),set()).add(identity)self.automation.update(event)if event.organization:self.organization_automation.update(event)55 unmodified linescommit=(previous.key,previous.identity.rsplit(':',1)[-1])self.commit_observations[commit].discard(identity)if not self.commit_observations[commit]:del self.commit_observations[commit]if previous.repo_uid:repo_key=(previous.key.partition('.')[0],previous.repo_uid)self.commits_by_repo_uid[repo_key].discard(identity)if not self.commits_by_repo_uid[repo_key]:del self.commits_by_repo_uid[repo_key]self.automation.update(None, previous)(self.organization_automation if previous.organization else self.personal_automation).update(None, previous)74 unmodified lines# A verified stable Hub ID keeps renamed histories linked.# Original personal attribution remains unchanged on transfer.by_uid = {(k.partition(':')[0],r.get('uid')):r for k,r in changed.items() if r.get('uid')}affected=set().union(*(self.commits_by_repo_uid.get(key,()) for key in by_uid))if aliases:affected.update(identity for identity,event in self.events.items()if event.key.endswith('.commit') and event.key.partition('.')[0]+':'+event.repo in aliases)for identity in affected:event=self.events.get(identity)if event is None:continuekind = event.key.partition('.')[0]row = by_uid.get((kind,event.repo_uid)) or aliases.get(kind + ':' + event.repo)if row and row.get('repo'):
15 unmodified lines16171819202112 unmodified lines34353637383991 unmodified lines13113213313413513673 unmodified lines2102112122132142153 unmodified lines21922022122222322435 unmodified lines26026126226326426526648 unmodified lines31531631731831932032129 unmodified lines35135235335435535635748 unmodified lines4064074084094104118 unmodified lines42042142242342442542642742815 unmodified linesMAX_NAMESPACES = 200MAX_NAMESPACE_LOOKUPS = 30MAX_TARGET_LOOKUPS = 100RESUME_NOTICE = 'Organization history is partially collected. Use the organization activity button to continue from the saved position.'ACCESS_NOTICE = ('Private organization access was refused (HTTP 403). Sign out and sign in again, ''authorize the relevant organizations, then retry organization activity. Your Hub account must also have access.')12 unmodified linesand isinstance(a.get('user'), str) and a['user'].lower() == username.lower() for a in authors)def discover(request, public, private, previous):names = dict(previous.get('namespaces', {}))scopes = {n:s for n,s in previous.get('namespace_scopes',{}).items() if n in names}91 unmodified linesfailed_slots=request.continuation_context.setdefault('failed_slots',set())state = deepcopy(request.sync.get('organizations', {}))state.setdefault('repos', {})public = HubClient(cancel)private = HubClient(cancel, request.token) if request.private and request.token else publicif not request.continuing:request.organization_visibility = {}73 unmodified linesfor namespace in ordered_names:hidden=names[namespace]if hidden and not request.private: continuekinds=list(PLURALS)if namespace==next_name and next_kind in kinds:offset=kinds.index(next_kind);kinds=kinds[offset:]+kinds[:offset]3 unmodified linesif slot in failed_slots:continuestate['next_slot']=slotlisting = listings.setdefault(slot, {'cursor': None, 'pending': [], 'complete': False})root = '/api/' + pluralfocused=listing['scope']=='repositories'visited = set()35 unmodified linesvisited.add(signature)listed += 1params = None if cursor else {'author': namespace, 'limit': 100,'full': 'true', 'sort': 'lastModified', 'direction': -1}inventory_client=public if listing.get('access_denied') else privatetry:rows, nxt = inventory_client.get(path, params)48 unmodified linesprevious = state['repos'].get(key, {})uid = item.get('_id') if isinstance(item.get('_id'), str) else ''if not previous and uid:previous = next((r for k, r in state['repos'].items() if k.startswith(kind + ':') and r.get('uid') == uid), {})if uid and previous.get('uid') and uid!=previous['uid']:previous={} # Same path, different repository: no shared cursor or head.uid=uid or previous.get('uid','')29 unmodified linesrow['cursor'] = safe_cursor(path, commit_root)state['repos'][key] = rowtry:commits, nxt = (private if visibility else public).get(path)except HubError as error:message = (ACCESS_NOTICE if error.status_code==403 else str(error)) if visibility else public_request_error(error, bool(item.get('gated')))row['error'] = message48 unmodified lineswarnings.append('An organization commit was unreadable or its repository identity could not be verified. Retry organization activity.')else:row['cursor'] = None if stop or not nxt else safe_cursor(nxt, commit_root)row['complete'] = row['cursor'] is Noneupdate(events=events, issues=issues, detail='Reading attributed organization commits',warnings=warnings[-1:] if invalid else [])8 unmodified linesrow.update(repo=repo, uid=uid, private=visibility)state['repos'][key] = rowif uid:for old_key, old_row in list(state['repos'].items()):if old_key != key and old_key.startswith(kind + ':') and old_row.get('uid') == uid:del state['repos'][old_key]if exhausted: breakif row.get('tail_complete'):# The saved tail is done; keep this metadata item until15 unmodified lines161718192021222312 unmodified lines363738394041424344454647484950515253545556575891 unmodified lines15015115215315415515615715815916016116216316473 unmodified lines2382392402412422432443 unmodified lines24824925025125225325425535 unmodified lines29129229329429529629729848 unmodified lines34734834935035135235335429 unmodified lines38438538638738838939039148 unmodified lines4404414424434444454464474484494508 unmodified lines45946046146246346446546646746815 unmodified linesMAX_NAMESPACES = 200MAX_NAMESPACE_LOOKUPS = 30MAX_TARGET_LOOKUPS = 100COMMIT_PAGE_SIZE = 1000 # Documented Hub maximum; returned/legacy cursors keep their size.FIRST_COMMIT_PAGE_SIZE = 100 # Small/unchanged histories rarely need a large response.RESUME_NOTICE = 'Organization history is partially collected. Use the organization activity button to continue from the saved position.'ACCESS_NOTICE = ('Private organization access was refused (HTTP 403). Sign out and sign in again, ''authorize the relevant organizations, then retry organization activity. Your Hub account must also have access.')12 unmodified linesand isinstance(a.get('user'), str) and a['user'].lower() == username.lower() for a in authors)def empty_public_kinds(namespace, request, client, known_kinds):"""Fresh explicit zeros can replace empty inventories, never private reads."""if request.private or len(known_kinds.get(namespace.lower(), ()))==len(PLURALS):return ()observations=request.continuation_context.setdefault('empty_public_kinds',{})if namespace not in observations:observations[namespace]=[]try:value,_=client.get('/api/organizations/'+quote(namespace,safe='')+'/overview')if isinstance(value,dict) and isinstance(value.get('name'),str) and value['name'].lower()==namespace.lower():observations[namespace]=[kind for kind,plural in PLURALS.items()if type(value.get('num'+plural.title())) is int and value['num'+plural.title()]==0]except HubError:pass # Optional hint: ordinary listings still establish coverage.return observations[namespace]def discover(request, public, private, previous):names = dict(previous.get('namespaces', {}))scopes = {n:s for n,s in previous.get('namespace_scopes',{}).items() if n in names}91 unmodified linesfailed_slots=request.continuation_context.setdefault('failed_slots',set())state = deepcopy(request.sync.get('organizations', {}))state.setdefault('repos', {})# Resolve stable IDs once instead of scanning every saved repository twice# per inventory row (quadratic for large organizations).by_uid = {}known_kinds = {}for key, row in state['repos'].items():if row.get('private') is False:known_kinds.setdefault(key.partition(':')[2].partition('/')[0].lower(),set()).add(key.partition(':')[0])if row.get('uid'):by_uid.setdefault((key.partition(':')[0], row['uid']), {})[key] = Nonepublic = HubClient(cancel)private = HubClient(cancel, request.token) if request.private and request.token else publicif not request.continuing:request.organization_visibility = {}73 unmodified linesfor namespace in ordered_names:hidden=names[namespace]if hidden and not request.private: continueempty_kinds=empty_public_kinds(namespace,request,public,known_kinds) if state['namespace_scopes'][namespace] in FULL_SCOPES else ()kinds=list(PLURALS)if namespace==next_name and next_kind in kinds:offset=kinds.index(next_kind);kinds=kinds[offset:]+kinds[:offset]3 unmodified linesif slot in failed_slots:continuestate['next_slot']=slotlisting = listings.setdefault(slot, {'cursor': None, 'pending': [], 'complete': False})if kind in empty_kinds and not listing['pending'] and not listing['cursor']:listing['complete']=Trueroot = '/api/' + pluralfocused=listing['scope']=='repositories'visited = set()35 unmodified linesvisited.add(signature)listed += 1params = None if cursor else {'author': namespace, 'limit': 100,'expand': ['sha','private','createdAt','lastModified'] + ([] if kind=='space' else ['gated']),'sort': 'lastModified', 'direction': -1}inventory_client=public if listing.get('access_denied') else privatetry:rows, nxt = inventory_client.get(path, params)48 unmodified linesprevious = state['repos'].get(key, {})uid = item.get('_id') if isinstance(item.get('_id'), str) else ''if not previous and uid:previous = next((state['repos'][k] for k in by_uid.get((kind,uid),{})if state['repos'].get(k,{}).get('uid')==uid), {})if uid and previous.get('uid') and uid!=previous['uid']:previous={} # Same path, different repository: no shared cursor or head.uid=uid or previous.get('uid','')29 unmodified linesrow['cursor'] = safe_cursor(path, commit_root)state['repos'][key] = rowtry:commits, nxt = (private if visibility else public).get(path,{'limit':FIRST_COMMIT_PAGE_SIZE} if path==commit_root else None)except HubError as error:message = (ACCESS_NOTICE if error.status_code==403 else str(error)) if visibility else public_request_error(error, bool(item.get('gated')))row['error'] = message48 unmodified lineswarnings.append('An organization commit was unreadable or its repository identity could not be verified. Retry organization activity.')else:row['cursor'] = None if stop or not nxt else safe_cursor(nxt, commit_root)if row['cursor'] and not resume and path==commit_root and len(commits)>=FIRST_COMMIT_PAGE_SIZE:# The first small page proves more relevant history is# needed. Restart with overlap at a larger page size;# never reinterpret a saved offset under a new limit.row['cursor']=commit_root+'?limit='+str(COMMIT_PAGE_SIZE)row['complete'] = row['cursor'] is Noneupdate(events=events, issues=issues, detail='Reading attributed organization commits',warnings=warnings[-1:] if invalid else [])8 unmodified linesrow.update(repo=repo, uid=uid, private=visibility)state['repos'][key] = rowif uid:for old_key in by_uid.get((kind,uid),{}):if old_key != key and state['repos'].get(old_key,{}).get('uid') == uid:del state['repos'][old_key]by_uid[(kind,uid)]={key:None}if exhausted: breakif row.get('tail_complete'):# The saved tail is done; keep this metadata item until
123456from datetime import datetime, timezoneVERSION = "0.5.31"FIRST_YEAR = 2022DATA_VERSION = 1SOURCE_VERSIONS = {s: 1 for s in ("repositories", "organizations", "community", "private_community", "likes", "upvotes", "papers", "blogs", "posts")}123456from datetime import datetime, timezoneVERSION = "0.5.32"FIRST_YEAR = 2022DATA_VERSION = 1SOURCE_VERSIONS = {s: 1 for s in ("repositories", "organizations", "community", "private_community", "likes", "upvotes", "papers", "blogs", "posts")}
123version https://git-lfs.github.com/spec/v1oid sha256:b8a77966387398050b80fb06eeec0b092f3b5cc1acde4b9052a8a1b92a666133size 55791512345678910111213141516"""Opt-in synthetic CPU benchmark; no Hub requests. Run with optional repo count."""import sys,time,jsonfrom pathlib import Pathsys.path[:0]=[str(Path(__file__).resolve().parents[1]),str(Path(__file__).resolve().parent)]from copy import deepcopyfrom datetime import datetime,timezonefrom pytest import MonkeyPatchfrom test_organizations import Hub,repository,runmp=MonkeyPatch();count=int(sys.argv[1]) if len(sys.argv)>1 else 5000h=Hub(repos=[{**repository('team/app'+str(i),'uid'+str(i)),'lastModified':'2025-01-01T00:00:00Z'} for i in range(count)])start=time.perf_counter();acc,updates,h,q=run(mp,h);cold=time.perf_counter()-startq.sync=deepcopy(acc.sync);saved=acc.bundle(datetime.now(timezone.utc));h.calls.clear()start=time.perf_counter();acc,updates,h,q=run(mp,h,q,saved);warm=time.perf_counter()-startassert updates[-1].status=='complete' and len(acc.sync['organizations']['repos'])==count and not acc.eventsprint(json.dumps({'repos':count,'cold_cpu_seconds':cold,'refresh_cpu_seconds':warm,'refresh_checkpoints':len(updates),'history_requests':sum('/commits/' in p for p,_,_ in h.calls)}))mp.undo()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100"""Compare anonymous organization extensions from a local public checkpoint.
No bucket reads/writes. The supplied checkpoint must be public-only. Each outputdirectory must be new; it contains the resulting full ledger and must stay local.See ORGANIZATION_PERFORMANCE.md for measured results and limitations."""import argparsefrom collections import Counterfrom copy import deepcopyimport gzipimport jsonfrom pathlib import Pathimport sysimport timefrom urllib.parse import urlparse
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--base', required=True, type=Path) parser.add_argument('--output', required=True, type=Path) parser.add_argument('--source-root', type=Path, default=Path(__file__).resolve().parents[1]) args = parser.parse_args() sys.path.insert(0, str(args.source_root.resolve())) from contrib import collection, storage, public_cache from contrib.domain import CollectionRequest from contrib.hub import HubClient
raw = args.base.read_bytes() saved = json.loads(gzip.decompress(raw) if raw.startswith(b'\x1f\x8b') else raw) if saved.get('private') is not False or any(e.get('private') for e in saved['events']): raise ValueError('Use a public-only saved checkpoint') identity = dict(username=saved['username'], year=saved['year'], owner='local-benchmark', owner_id=saved['owner_id']) storage.validate_bundle(saved, CollectionRequest(**identity)) saved['events'] = [e for e in saved['events'] if not e.get('organization')] saved['sync'].pop('organizations', None) saved['sources']['organizations'] = dict(status='not_requested', detail='', pages=0, scanned=0) saved['warnings'] = [w for w in saved.get('warnings', []) if not w.startswith('organizations:')] saved['issues'] = [i for i in saved.get('issues', []) if i['source'] != 'organizations'] saved.pop('automation', None) saved['collection_scope'] = 'personal' args.output.mkdir(parents=True, exist_ok=False) checkpoint = args.output / 'checkpoint.json.gz'
class LocalStore: bucket_id = 'validation-local' private_backup_available = False editorial_notice = ''
def __init__(self, query): self.query = query
def load(self, resume=False): return deepcopy(json.loads(gzip.decompress(checkpoint.read_bytes())) if checkpoint.exists() else saved)
def save(self, bundle): storage.validate_bundle(bundle, self.query) checkpoint.write_bytes(gzip.compress(json.dumps(bundle).encode())) return self.bucket_id
storage.storage_enabled = lambda query: True storage.BucketStore = LocalStore public_cache.enabled = lambda query: False calls = Counter() failures = Counter() original_get = HubClient.get
def measured_get(client, path, *positional, **kwargs): route = urlparse(path).path kind = ('history' if '/commits/' in route else 'inventory' if route in ('/api/models', '/api/datasets', '/api/spaces') else 'metadata') calls[kind] += 1 try: return original_get(client, path, *positional, **kwargs) except Exception as error: failures[str(getattr(error, 'status_code', None) or type(error).__name__)] += 1 raise
HubClient.get = measured_get results = [] for mode in ('cold', 'refresh'): calls.clear() failures.clear() query = CollectionRequest(**identity, scan_scope='organizations') start = time.monotonic() for snapshot in collection.stream(query, 'organization-benchmark', True): pass result = dict(mode=mode, seconds=time.monotonic()-start, raw_total=sum(map(sum, snapshot['bins'].values())), organization_total=sum(map(sum, snapshot['organization_bins'].values())), calls=dict(calls), failures=dict(failures), source=snapshot['sources']['organizations']) results.append(result) (args.output / (mode+'-snapshot.json')).write_text(json.dumps(snapshot)) (args.output / 'results.json').write_text(json.dumps(results, indent=2)) print(json.dumps(result), flush=True)
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116"""Page contracts and linear identity lookups for large organization inventories."""from copy import deepcopyfrom dataclasses import replacefrom datetime import datetime, timezonefrom threading import Eventimport pytestfrom contrib.collectors import organizations as orgfrom contrib.domain import ActivityEvent, Update, timestampfrom contrib.aggregation import Accumulatorfrom contrib.continuation import run_sourcefrom test_organizations import Hub, repository, commit, runfrom test_storage import request
def test_large_page_uses_explicit_limit_and_follows_legacy_links_verbatim(monkeypatch): root='/api/spaces/team/app/commits/main' legacy='https://huggingface.co'+root+'?p=7&limit=50' h=Hub({root:([commit('a')],legacy),legacy:([commit('b')],None)}) acc,updates,h,q=run(monkeypatch,h) calls=[(p,params) for p,params,_ in h.calls if '/commits/' in p] assert calls==[(root,{'limit':100}),(legacy,None)] assert len(acc.events)==2 and updates[-1].status=='complete'
def test_inventory_returns_only_collection_metadata_and_spaces_have_no_gated_expand(monkeypatch): _,_,h,_=run(monkeypatch) for path,params,token in h.calls: if path in ('/api/models','/api/datasets','/api/spaces'): assert 'full' not in params assert set(params['expand'])=={'sha','private','createdAt','lastModified'} | (set() if path=='/api/spaces' else {'gated'}) assert params['limit']==100 and params['sort']=='lastModified'
def test_large_pages_keep_automatic_continuation_and_exact_dedup(monkeypatch): root='/api/spaces/team/app/commits/main';nxt=root+'?p=1&limit=1000';wide=root+'?limit=1000' h=Hub({root:([commit(str(i)) for i in range(100)],root+'?p=1&limit=100'), wide:([commit(str(i)) for i in range(1000)],nxt), nxt:([commit('999'),commit('1000')],None)}).install(monkeypatch) monkeypatch.setattr(org,'MAX_COMMIT_PAGES',1) q=request();acc=Accumulator(q);updates=[] def receive(u):updates.append(u);acc.apply(u) run_source(org.collect_organizations,q,'organizations',Event(),receive) assert updates[-1].status=='complete' and len(acc.events)==1001 assert [p for p,_,_ in h.calls if '/commits/' in p]==[root,wide,nxt] assert acc.sync['organizations']['repos']['space:team/app']['cursor'] is None
def test_uid_lookup_does_not_reuse_a_recreated_path_for_the_old_repository(monkeypatch): # A stale UID index entry at the same path must not masquerade as a rename. q=request();q.sync={'organizations':{'namespaces':{'team':False},'namespace_scopes':{'team':'member'}, 'inventory_complete':True,'repos':{'space:team/app':{'uid':'old-id','repo':'team/app','private':False,'complete':True,'listing_sha':'a','head':'a'}}}} h=Hub(repos=[repository(uid='replacement-id',sha='replacement'),repository('team/moved','old-id',sha='a')]) h.routes={'/api/spaces/team/app/commits/main':([commit('replacement')],None), '/api/spaces/team/moved/commits/main':([commit('a')],None)} acc,updates,h,_=run(monkeypatch,h,q) assert updates[-1].status=='complete' assert {(e.repo_uid,e.identity) for e in acc.events.values()}=={('replacement-id','replacement-id:replacement'),('old-id','old-id:a')}
class ObservedLedger(dict): scans=0 def values(self):self.scans+=1;return super().values() def items(self):self.scans+=1;return super().items()
def test_unrelated_inventory_update_does_not_walk_the_whole_event_ledger(): q=request();acc=Accumulator(q) for i in range(2000): acc.add(ActivityEvent('space.commit','personal:'+str(i),timestamp('2026-04-01'),repo='fffiloni/app',repo_uid='personal')) acc.events=ObservedLedger(acc.events) acc.apply(Update('organizations',checkpoint={'organization_state':{'repos':{ 'space:team/new':{'repo':'team/new','uid':'unrelated','private':False}}}})) assert acc.events.scans==0 and len(acc.events)==2000
def test_indexed_rename_enriches_only_matching_commits_and_is_removed_on_replacement(): q=request(private=True);acc=Accumulator(q) e=ActivityEvent('space.commit','stable:sha',timestamp('2026-04-01'),repo='team/old',repo_uid='stable',organization=True) acc.add(e);acc.add(replace(e,identity='other:sha',repo_uid='other',repo='team/fork')) acc.events=ObservedLedger(acc.events) acc.apply(Update('organizations',checkpoint={'organization_state':{'repos':{ 'space:team/new':{'repo':'team/new','uid':'stable','private':True}}}})) moved=acc.events[('space.commit','stable:sha')] assert moved.repo=='team/new' and moved.private and acc.events.scans==0 assert acc.events[('space.commit','other:sha')].repo=='team/fork' acc.remove(moved) assert ('space','stable') not in acc.commits_by_repo_uid assert len(acc.events)==1
def test_explicit_public_zero_skips_only_empty_kind_and_refresh_rechecks(monkeypatch): h=Hub();h.install(monkeypatch) cls=org.HubClient;original=cls.get;counts={'numModels':0,'numDatasets':0,'numSpaces':1} def get(self,path,params=None): if path=='/api/organizations/team/overview': h.calls.append((path,params,self.token));return {'name':'team',**counts},None return original(self,path,params) monkeypatch.setattr(cls,'get',get) q=request();acc=Accumulator(q) org.collect_organizations(q,Event(),acc.apply) assert not any(p in ('/api/models','/api/datasets') for p,_,_ in h.calls) assert len(acc.events)==1 and acc.snapshot['sources']['organizations']['status']=='complete' q.sync=deepcopy(acc.sync);h.calls.clear();counts['numModels']=1 org.collect_organizations(q,Event(),acc.apply) assert any(p=='/api/models' for p,_,_ in h.calls),'zero hints expire with the scan'
@pytest.mark.parametrize('private,bad',[(True,False),(False,True)])def test_public_zero_never_certifies_private_inventory_or_malformed_counts(monkeypatch,private,bad): h=Hub();h.install(monkeypatch);cls=org.HubClient;original=cls.get def get(self,path,params=None): if path=='/api/organizations/team/overview':return {'name':'team','numModels':False if bad else 0,'numDatasets':'0' if bad else 0,'numSpaces':None if bad else 0},None return original(self,path,params) monkeypatch.setattr(cls,'get',get) q=request(private=private);acc=Accumulator(q);org.collect_organizations(q,Event(),acc.apply) assert {p for p,_,_ in h.calls if p in ('/api/models','/api/datasets','/api/spaces')}=={'/api/models','/api/datasets','/api/spaces'}CHANGELOG.md+7
ORGANIZATION_PERFORMANCE.mdAdded+97
PUBLIC_CACHE.md+6
README.md+7-1
VALIDATION.md+13-1
contrib/aggregation.py+14-2
contrib/collectors/organizations.py+45-5
contrib/config.py+1-1
releases/HF-Contrib-v2-0.5.32.zipAdded+3
tests/benchmark_organization_scaling.pyAdded+16
tests/benchmark_organization_scan.pyAdded+100
tests/test_organization_performance.pyAdded+116