Skip to content

feat: implement hybrid cache architecture - #1246

Open
fabiovincenzi wants to merge 84 commits into
finos:mainfrom
fabiovincenzi:feature/hybrid-cache
Open

fabiovincenzi wants to merge 84 commits into
finos:mainfrom
fabiovincenzi:feature/hybrid-cache

Conversation

@fabiovincenzi

@fabiovincenzi fabiovincenzi commented Oct 13, 2025 •

Copy link
Copy Markdown
Contributor

Issue: #1207

Summary

An opt-in repository cache for the pullRemote step. GitProxy keeps one bare mirror per upstream repository and only fetches the new commits on each push, then clones the per-push working copy locally from the mirror. With the cache disabled (the default) pullRemote is unchanged.

On backstage/backstage (8.7 GB pack), the pullRemote step of a one-commit push goes from 145 s to 6.4 s on a cache hit, with peak memory from 3.3 GB to about 100 MB and no event-loop stalls (benchmark). The first push of a repository is slower (full history instead of a shallow clone).

How it works

  • createPullRemote() returns PullRemoteHTTPSCached / PullRemoteSSHCached when cache.enabled is true. Both hand a protocol-specific RemoteAccess to performCachedClone().
  • Mirror at <cacheDir>/<host>__<project>__<repo>-<sha256>: git clone --bare on a miss, git fetch --prune on a hit. A fetch failure on a readable mirror fails the push and keeps the mirror; only a corrupted mirror is rebuilt. Clones go through a .staging-* folder and are moved into place only on success.
  • Working copy: local git clone from the mirror into the usual .remote/<hash>/ folder, removed by clearBareClone as before.
  • Concurrency: a per-repository lock serialises work on one mirror; different repositories run in parallel. Locked repositories are never evicted.
  • Eviction: LRU by mtime above maxSizeGB or maxRepositories; the mirror just used is always kept.
  • All git commands run through async spawn with a configurable timeout that kills the whole process tree.

Security

  • Every push authenticates against the upstream with its own credentials, so the cache never gives access to a repository the client could not clone.
  • HTTPS credentials are passed through GIT_CONFIG_* environment variables as an http.<origin>.extraHeader, never on the command line, in a URL or in the mirror's config. credential.helper is reset and GIT_TERMINAL_PROMPT=0.
  • Git runs isolated from the host's configuration (GIT_CONFIG_NOSYSTEM=1, empty HOME), so /etc/gitconfig, ~/.gitconfig and ~/.netrc never apply to a client's clone.

Configuration

{
  "cache": {
    "enabled": true,
    "maxSizeGB": 10,
    "maxRepositories": 50,
    "cacheDir": "./.repo-cache",
    "gitTimeoutSeconds": 3600
  }
}

All settings are optional; only enabled is needed. The cache lives outside ./.remote, which is emptied on startup. Requires git 2.31 or later, checked at startup when the cache is enabled. Several GitProxy instances must not share a cacheDir.

Docs: website/docs/deployment.mdx (Repository Cache) and src/proxy/processors/push-action/README.md.

Tests

  • test/processors/cachedClone.test.ts, cacheManager.test.ts, gitOperations.test.ts: offline, against a local bare remote and local HTTP server (keys, miss/hit/rebuild, concurrency, eviction, credentials, host-config isolation, timeouts).
  • test/processors/hybridCache.integration.test.ts: end-to-end against github.com, only with RUN_NETWORK_TESTS=true.

@netlify

netlify Bot commented Oct 13, 2025 •

Copy link
Copy Markdown

✅ Deploy Preview for endearing-brigadeiros-63f9d0 ready!

Built without sensitive environment variables

Name Link
🔨 Latest commit 9b5df9f
🔍 Latest deploy log https://app.netlify.com/projects/endearing-brigadeiros-63f9d0/deploys/6b0852fa9b4b691cc3a1a21f
😎 Deploy Preview https://deploy-preview-1246.git-proxy.preview.finos.org
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@codecov

codecov Bot commented Oct 13, 2025 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.47619% with 30 lines in your changes missing coverage. Please review.
✅ Project coverage is 89.03%. Comparing base (7ffaf8f) to head (9b5df9f).

Files with missing lines Patch % Lines
src/proxy/processors/push-action/git-operations.ts 87.91% 5 Missing and 6 partials ⚠️
src/proxy/processors/push-action/cache-manager.ts 91.81% 4 Missing and 5 partials ⚠️
...rc/proxy/processors/push-action/PullRemoteHTTPS.ts 0.00% 4 Missing ⚠️
src/proxy/processors/push-action/PullRemoteSSH.ts 89.47% 2 Missing ⚠️
src/proxy/processors/push-action/metrics.ts 84.61% 0 Missing and 2 partials ⚠️
...roxy/processors/push-action/PullRemoteSSHCached.ts 91.66% 0 Missing and 1 partial ⚠️
src/proxy/processors/push-action/cachedClone.ts 98.03% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1246      +/-   ##
==========================================
+ Coverage   88.98%   89.03%   +0.04%     
==========================================
  Files         132      138       +6     
  Lines        7281     7586     +305     
  Branches     1365     1423      +58     
==========================================
+ Hits         6479     6754     +275     
- Misses        494      510      +16     
- Partials      308      322      +14     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@fabiovincenzi
fabiovincenzi marked this pull request as ready for review October 22, 2025 14:13

@06kellyjac 06kellyjac left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm looking forward to faster pulls!

Caches are a common place for logic or security problems so we may want added scrutiny and testing for this PR to be extra safe :)

Added some thoughts, not ran this locally just yet.

Comment thread src/config/index.ts Resolved

@jescalada jescalada left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just a code review for now - I'll be testing the code later!

I was wondering if you could do some profiling to verify/document the speed improvements with this PR. Would be nice to try it out with massive repos (for example https://github.com/backstage/backstage which is >10GB) to see the difference.

I'll try to do some profiling soon as well 🙂

@06kellyjac

Copy link
Copy Markdown
Contributor

why on earth is backstage's repo 10GB? 😭
Even nixpkgs is only 6.1GB ATM on my machine

@jescalada

Copy link
Copy Markdown
Contributor

@06kellyjac It might be because of the tons of plugins that come with the repo (many of which have redundant components). Pulling with git clone --filter=blob:none https://github.com/backstage/backstage.git seems to make things a lot more speedy, however I'm not sure if we want to do things that way in the pullRemote. Perhaps a config option to filter out the BLOBs could help with these massive repos?

@kriswest kriswest removed this from the 2.4.0 milestone Nov 2, 2026

@jescalada jescalada left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just a few more comments from me (and Claude). 👍🏼

Also, I think it'd be great to document this a bit better (for example in website/docs/deployment), so users (and agents) are aware of the caching feature even if it's disabled by default,

Comment thread config.schema.json Resolved
Comment thread config.schema.json Resolved
Comment thread proxy.config.json Resolved

@jescalada jescalada left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for fixing all those issues! I had Claude do some benchmarking here and things are looking great. Check out this gist for the full details: https://gist.github.com/jescalada/9c0e93aec698cc5a73f3f53c2de9b3ff

I also asked it to find any other bugs or security flaws, and these are the most notable ones (the rest are at the bottom of that gist although I think they're trivial/not applicable):


AI-review:

  1. User config ignored

The user config is ignored for every cache setting except enabled. cache-manager.ts builds the cacheManager singleton when the module is imported. index.ts imports ./src/proxy statically, before setConfigFile(argv.c) and initUserConfig() run. As a result cacheDir, maxSizeGB, maxRepositories and gitTimeoutSeconds always come from the bundled proxy.config.json.

Fix: read the config lazily in CacheManager, either through getters that call getCacheConfig() or by creating the instance on first use.

  1. Incompatibility with current Docker setup

The documented Docker volume stops the proxy from starting, and without it the cache is wiped on every restart. proxyPreparations() runs fs.rmSync('./.remote', { recursive: true, force: true }). With the suggested -v $(pwd)/cache:/app/.remote/cache mount, that call throws EBUSY: resource busy or locked, rmdir './.remote/cache' (reproduced with a bind mount), and start() rejects. Without a mount, the default cacheDir lives inside .remote, so every restart deletes the cache.

Fix: move the default cacheDir out of .remote (or skip it in the startup sweep), and remove leftover .staging-* folders at startup. As things stand they leak (8.5 GiB per crash on Backstage) whenever cacheDir is outside .remote.

  1. Git 2.31 requirement not enforced (check if this is necessary first)

git 2.31 or newer is required, but nothing checks for it. Older git ignores GIT_CONFIG_COUNT. On those versions the Authorization header is never sent, and credential.helper is never reset, so git falls back to whatever credential helpers the host has configured. Debian 11 ships git 2.30 and Ubuntu 20.04 ships 2.25.

Fix: check git --version at startup when the cache is enabled and refuse to start if it is too old. (Warning: Claude didn't actually test against an older git version)

  1. Timeout doesn't stop git immediately

The timeout does not reliably stop git. runGit sends SIGTERM to the git parent and rejects immediately, without waiting for close or killing the process group. buildBare then deletes the staging dir while children such as index-pack may still be running. After the 600 s timeout fired in the benchmark, the process took another ~110 s to exit, which fits a child still holding the stderr pipe. In a long-running proxy, the repo lock is released while the old index-pack keeps using CPU and the next push starts another full clone.

Fix: spawn with detached: true, kill -pid, escalate to SIGKILL after a grace period, and settle the promise on close.

@jescalada jescalada left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! 🚀

@jescalada jescalada left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just one more thing left to fix the CI 🙂

// Dot-prefixed so getCacheStats() and eviction ignore it while it is built
const staging = path.join(
path.dirname(bareRepo),
`.staging-${path.basename(bareRepo)}-${crypto.randomUUID()}`,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is making Windows tests fail due to very long filenames

Suggested change
`.staging-${path.basename(bareRepo)}-${crypto.randomUUID()}`,
`.staging-${crypto.randomUUID()}`,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(May still need npm run format after applying this)


Git commands on the mirror use `--git-dir`, so a broken mirror inside another repository (such as the GitProxy checkout around `./.repo-cache`) is never mistaken for that repository.

Every clone into the cache is done in a dot-prefixed staging folder (`.staging-<key>-<uuid>`) and only moved into place once it succeeded, so a failed or interrupted clone never leaves a half-written mirror behind. Staging folders are ignored by the cache statistics and by eviction, and leftovers from a crash are removed at startup.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For accuracy if the previous change is applied

Suggested change
Every clone into the cache is done in a dot-prefixed staging folder (`.staging-<key>-<uuid>`) and only moved into place once it succeeded, so a failed or interrupted clone never leaves a half-written mirror behind. Staging folders are ignored by the cache statistics and by eviction, and leftovers from a crash are removed at startup.
Every clone into the cache is done in a dot-prefixed staging folder (`.staging-<uuid>`) and only moved into place once it succeeded, so a failed or interrupted clone never leaves a half-written mirror behind. Staging folders are ignored by the cache statistics and by eviction, and leftovers from a crash are removed at startup.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Improve push flexibility and pull times

6 participants