Skip to content

perf(hosts): batch manager updates for bulk enable and disable - #945

Merged
T3ST3ST3R0N merged 1 commit into
PasarGuard:devfrom
dr-hoseyn:codex/perf-bulk-host-state
Oct 8, 2026
Merged

T3ST3ST3R0N merged 1 commit into
PasarGuard:devfrom
dr-hoseyn:codex/perf-bulk-host-state

Conversation

@dr-hoseyn

@dr-hoseyn dr-hoseyn commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Bulk enable/disable currently calls HostManager.add_host once per changed host, repeating inbound synchronization, commits, cache invalidation and full host-state persistence. Pass the refreshed changed hosts to add_hosts once, then emit the existing per-host notifications and logs. No-op selections still skip HostManager, and missing IDs still return 404 before mutation.

Measured improvement

Compared the current dev implementation with this change for 100 changed hosts in a 1,000-host fixture, for both enable and disable. The local harness executed the actual operation and HostManager code, including host preparation and state serialization; database, core lookup, NATS I/O, notifications and cache invalidation were instrumented with mocks.

Operation on the originating worker Before After Reduction
Inbound synchronization calls 100 1 99%
Total DB commit calls, including the initial host update 101 2 98.02%
Full state KV writes, with KV configured 100 1 99%
Cache resets through the local manager path 100 1 99%
Cache resets through the NATS manager path 200 2 99%

These percentages describe operation counts, not measured end-to-end latency. Per-host NATS messages remain 100, and remote subscriber work is unchanged. Final host state and response IDs matched the baseline.

Validation

  • Existing host API suite: 9 passed, using a dedicated SQLite database.
  • Local before/after checks: enable, disable, no-op selections and missing IDs on both local and NATS paths; notification and refresh counts checked.
  • Ruff lint/format and git diff --check passed.
  • Reviewed related existing PRs and current dev; no duplicate implementation found.

Only app/operation/host.py is changed. No test, documentation or benchmark files are included.

Summary by CodeRabbit

  • Bug Fixes
    • Bulk host status changes are now applied together before notifications are sent, keeping the update order consistent.
    • When no hosts have changed, no host update is sent.

@coderabbitai

coderabbitai Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Advanced

Run ID: 46c1b6d2-798e-413a-b855-21b8bb0dfe93

📥 Commits

Reviewing files that changed from the base of the PR and between 26047f6 and 1a14cdc.

📒 Files selected for processing (1)
  • app/operation/host.py

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 5 remain after this review.


Walkthrough

The host operation now sends changed hosts to host_manager.add_hosts in one call before scheduling per-host notifications. It skips the manager call when no hosts require updates.

Changes

Host update batching

Layer / File(s) Summary
Batch updates before notifications
app/operation/host.py
The operation calls host_manager.add_hosts once with all changed hosts, when the list is non-empty. It schedules per-host notifications afterward.

Priority: ⬇️ Low

Estimated code review effort: 2 (Simple) | ~5 minutes

Change: Refactor

Suggested reviewers: m03ed

Merge Risk: ⚪ Minimal · up to 1a14c

Each changed host still receives its manager update and notification. The batching change is ready to merge.

Security Architecture Review

Security architecture risk: 🟡 Moderate · up to 1a14c

A failed bulk disable can leave hosts in cached host state after their database rows have been disabled. Batching can increase the number affected by one synchronization failure. The existing permission checks remain in place.

Retained concerns

  • Medium · security · inferred: A failure during batched NATS removal can leave all selected disabled hosts in the originating worker's cached host state, rather than leaving only hosts not yet processed by the former per-host flow.
Security review details

Security Blast Radius

  • inferred — One interrupted NATS batch can affect the originating worker's cached state for the entire selected disable set; other workers may have processed a different subset of published messages.

Security Findings and Attack Paths

  • inferred — The identified path requires an authorized bulk disable followed by a synchronization failure. It establishes possible stale host state, not a verified route for an unauthorized caller or a verified downstream access bypass.

Trust Boundaries and Controls

  • observed — The routes still require hosts:update permission and pass the selected IDs through the existing operation. No new public entrypoint or weaker authorization dependency is shown.

Resilience and Maintainability Implications

  • inferred — The database-to-manager consistency gap predates this change, but delaying all local NATS-batch updates until publication completes widens its failure scope. Local cache updates use a lock; that lock cannot undo an earlier commit or partial publication.

Hardening Proposals

  • proposed — Define recovery or reconciliation for a failed batch so committed disabled state is eventually reflected in local, remote, and persisted manager state.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 1 functions across 1 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately and concisely describes the main change: batching host manager updates for bulk enable and disable operations.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
  • Fix all pre-merge checks with AI
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

A rabbit sees hosts gathered as one,
The batch update is sent and done.
Then notes go hopping, one by one,
No batch is sent when changes are none.
Soft paws celebrate the run.

Comment @coderabbitai help to get the list of available commands.

@dr-hoseyn

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@T3ST3ST3R0N
T3ST3ST3R0N merged commit 9d69fee into PasarGuard:dev Oct 8, 2026
10 checks passed
@T3ST3ST3R0N

Copy link
Copy Markdown
Collaborator

Thanks, merged. Since add_host is just add_hosts with one item, batching keeps the behaviour identical while dropping the repeated per-host work.

Free-Guy-IR added a commit to Free-Guy-IR/panel that referenced this pull request Nov 2, 2026
… to ff6e596

Every Port queue line in the panel and side-repository ledgers now says
`security: yes` or `security: no`. Security: c9b445a (passkey client rename),
eb50bfd, PasarGuard#938, PasarGuard#940, PasarGuard#942, the cryptography 50.0.2 security release, and the ten
commits of upstream's PasarGuard#979 permission-leak batch (user list scopes, API-key
permissions, HWID visibility, users.read, the Telegram inline search), which no
branch ports yet.

Checked with git ls-remote on 2026-10-09: upstream dev moved to ff6e596. The
PasarGuard#979 batch, the node RPC fixes (PasarGuard#977, PasarGuard#978), the core-deletion restart (PasarGuard#934),
dashboard fixes (PasarGuard#852, PasarGuard#907, PasarGuard#949, PasarGuard#952), performance changes (PasarGuard#945, PasarGuard#853, PasarGuard#855) and
the merged dependabot bumps (ruff, uvloop, fastapi) join the queue; the ruff and
uvloop conditional waivers ended when upstream merged them. Waived: PasarGuard#980 and its
branch commit (the Telegram notifier workflow the fork deleted) and the superseded
fastapi dependabot head b021d6f. The refs snapshot records the five new heads.
Fork core-kit main 90701408 now contains upstream d2ecb5bd, so that ledger is empty.
No side repository gained an upstream commit since 2026-10-07.
Free-Guy-IR pushed a commit to Free-Guy-IR/panel that referenced this pull request Nov 3, 2026
…Guard#945)

Co-authored-by: etm <etm@LAPTOP-62O1BVSJ>

(cherry picked from commit 9d69fee)

Applied cleanly. tests/api/test_host_bulk_manager_batch.py fails on the
base (one host manager refresh per host) and passes after the pick (one
add_hosts call carrying every toggled host).
Free-Guy-IR added a commit to Free-Guy-IR/panel that referenced this pull request Nov 3, 2026
…refresh

Since the bulk enable and disable batch (9d69fee, PasarGuard#945) every toggled
host goes through one add_hosts call. When _prepare_host_entry raised for
one host, which only happens on bulk enable, the whole call aborted after
the database commit: no host of the batch reached the cache, no
notification was sent, and the request answered 500 although the hosts
were already enabled in the database. The per-host loop before PasarGuard#945 had
already applied hosts 1..k-1, so the batch widened the failure.

The host isolation from upstream 59c3b62 (PasarGuard#1053) is ported: a host
whose subscription settings cannot be prepared is logged and skipped,
which is what a full refresh and the startup rebuild then also do, and a
download host that cannot be prepared is left out of its parent instead
of failing the parent. The cache therefore equals a rebuild from the
database, the rest of the batch is served, and the request answers 200.
The rules for missing, disabled or unserved xHTTP download hosts
(omit_download_settings, the 409 on deleting a used download host and the
dependent rebuild on bulk toggle) belong to the download-host part of the
same upstream commit and are not ported here.

tests/api/test_host_bulk_enable_isolation.py fails on the base (500 with
TypeError) and passes here.

Upstream: 59c3b62 (host isolation hunk only)
Free-Guy-IR added a commit to Free-Guy-IR/panel that referenced this pull request Nov 3, 2026
… newer edit

A bulk enable or disable hands every toggled host to one add_hosts call
(9d69fee, PasarGuard#945). The host manager prepared those hosts from the ORM
objects the caller had refreshed before the call and wrote them into the
cache with no ordering check. A single-host edit or delete that committed
and updated the cache while the bulk call was still preparing was then
overwritten: the cache kept the old address, or served a deleted host
again, until the next write or restart. The per-host loop before PasarGuard#945
had the same race over a shorter window.

Every host-manager write now commits, takes a per-host stamp, and only
then re-reads its hosts from the database with populate_existing, so the
read sees every commit made before the stamp. The cache keeps an entry
only when its stamp is not older than the last one applied to that host,
and a remove takes a fresh stamp too. For writes of a host's own row in
one worker, the write that lands last in the cache therefore carries
that row as it was after the last commit to it. This commit does not
cover the other inputs of a cache entry: the served inbound list is
still read before the stamp, and an xHTTP download host is still read
from the session's identity map; later commits in this batch fix both.
A host the re-read no longer finds is removed. setup_local takes its
stamp before its full read and does not re-read. Messages from other
NATS workers carry no stamp and apply as before.

tests/api/test_host_bulk_cache_interleaving.py pauses the bulk enable
before add_hosts and before the cache write, runs a single-host edit or
delete to completion, resumes, and compares the cache with the database.
All four cases fail on the base (the cache keeps old.example.com, or the
deleted host) and pass here.
Free-Guy-IR pushed a commit to Free-Guy-IR/panel that referenced this pull request Nov 4, 2026
…Guard#945)

Co-authored-by: etm <etm@LAPTOP-62O1BVSJ>

(cherry picked from commit 9d69fee)

Applied cleanly. tests/api/test_host_bulk_manager_batch.py fails on the
base (one host manager refresh per host) and passes after the pick (one
add_hosts call carrying every toggled host).
Free-Guy-IR added a commit to Free-Guy-IR/panel that referenced this pull request Nov 4, 2026
…refresh

Since the bulk enable and disable batch (9d69fee, PasarGuard#945) every toggled
host goes through one add_hosts call. When _prepare_host_entry raised for
one host, which only happens on bulk enable, the whole call aborted after
the database commit: no host of the batch reached the cache, no
notification was sent, and the request answered 500 although the hosts
were already enabled in the database. The per-host loop before PasarGuard#945 had
already applied hosts 1..k-1, so the batch widened the failure.

The host isolation from upstream 59c3b62 (PasarGuard#1053) is ported: a host
whose subscription settings cannot be prepared is logged and skipped,
which is what a full refresh and the startup rebuild then also do, and a
download host that cannot be prepared is left out of its parent instead
of failing the parent. The cache therefore equals a rebuild from the
database, the rest of the batch is served, and the request answers 200.
The rules for missing, disabled or unserved xHTTP download hosts
(omit_download_settings, the 409 on deleting a used download host and the
dependent rebuild on bulk toggle) belong to the download-host part of the
same upstream commit and are not ported here.

tests/api/test_host_bulk_enable_isolation.py fails on the base (500 with
TypeError) and passes here.

Upstream: 59c3b62 (host isolation hunk only)
Free-Guy-IR added a commit to Free-Guy-IR/panel that referenced this pull request Nov 4, 2026
… newer edit

A bulk enable or disable hands every toggled host to one add_hosts call
(9d69fee, PasarGuard#945). The host manager prepared those hosts from the ORM
objects the caller had refreshed before the call and wrote them into the
cache with no ordering check. A single-host edit or delete that committed
and updated the cache while the bulk call was still preparing was then
overwritten: the cache kept the old address, or served a deleted host
again, until the next write or restart. The per-host loop before PasarGuard#945
had the same race over a shorter window.

Every host-manager write now commits, takes a per-host stamp, and only
then re-reads its hosts from the database with populate_existing, so the
read sees every commit made before the stamp. The cache keeps an entry
only when its stamp is not older than the last one applied to that host,
and a remove takes a fresh stamp too. For writes of a host's own row in
one worker, the write that lands last in the cache therefore carries
that row as it was after the last commit to it. This commit does not
cover the other inputs of a cache entry: the served inbound list is
still read before the stamp, and an xHTTP download host is still read
from the session's identity map; later commits in this batch fix both.
A host the re-read no longer finds is removed. setup_local takes its
stamp before its full read and does not re-read. Messages from other
NATS workers carry no stamp and apply as before.

tests/api/test_host_bulk_cache_interleaving.py pauses the bulk enable
before add_hosts and before the cache write, runs a single-host edit or
delete to completion, resumes, and compares the cache with the database.
All four cases fail on the base (the cache keeps old.example.com, or the
deleted host) and pass here.
Free-Guy-IR added a commit to Free-Guy-IR/panel that referenced this pull request Nov 4, 2026
…-w2h3 b616493) into r10/train-q

The B-SUB stack is merged, not rebased: it already carries three merges
of main and two side merges, and linearizing it reopens conflicts those
merges resolved (add/add in tests/api/test_host_bulk_manager_batch.py,
where main's 8f1c77e and the stack's e31f0a1 both port PasarGuard#945). The
merge keeps every pick SHA the ledger names. UPSTREAM_SYNC.md: the
8a706e9 and 8ae9e31 port queue rows are both dropped, since
the stack ports the first and port/b-dash-v560 the second.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants