Skip to content

feat(client): implement FastStart for quick connection, background resolver discovery and scoring, autonomous multi-resolver pool lifecycle. - #205

Merged
masterking32 merged 4 commits into
masterking32:mainfrom
taskkillstar:feat/fast-start-resolvers
Nov 14, 2026
Merged

masterking32 merged 4 commits into
masterking32:mainfrom
taskkillstar:feat/fast-start-resolvers

Conversation

@taskkillstar

@taskkillstar taskkillstar commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

Summary

When configured with large resolver lists (e.g. 50–100+ endpoints), the client previously blocked session initialization and local proxy (SOCKS5/DNS) startup until 100% of all resolvers were synchronously probed for MTU.

This pull request implements an autonomous multi-resolver domain and path pool lifecycle architecture for MasterDnsVPN. It evolves the client from static resolver rotation to an event-driven, authoritative ResolverPool with rate-limited background discovery, pipelined micro-burst qualification, and asynchronous ranked persistence.


Key Architectural Components

  1. Authoritative ResolverPool:

    • Manages candidate lifecycle across 4 distinct states: Checking, Active, Standby, and Ineligible.
    • Preserves distinct endpoint diversity quotas (preventing single-endpoint monopolization).
    • Enforces a unified 15% replacement margin before displacing an incumbent active path.
  2. Asynchronous ResolverDiscoveryEngine:

    • Discovers and validates candidate resolvers in the background without blocking foreground tunnel traffic.
    • Paced by a token-bucket BackgroundQueryLimiter to strictly enforce background query budgets (default: 15 QPS burst, 15 QPS sustained).
  3. Micro-Burst Throughput & MTU Qualification:

    • Pipelined UDP probe trains measure true transit latency, loss ratios, and MTU envelopes.
    • Detects upstream rate-limiting and burst drops before admitting candidates to the active pool.
  4. Asynchronous Ranked Persistence Writer:

    • Saves ranked resolver list snapshots to disk in the background.
    • Employs coalesce delay and a 30-second MinWriteInterval to prevent disk thrashing during traffic bursts, while guaranteeing immediate flushes on shutdown.
  5. Live Telemetry & Shared Path Evaluation:

    • Introduces composite scoring that unifies latency and packet loss.
    • Live loss tracking even when auto-disable is disabled, ensuring dynamic scoring accurately reflects degraded paths.

Acceptance & Benchmark Evidence

Verified via TestIntegratedResolverManagerAcceptance:

  • Readiness Time ($T_{ready}$): ~20 ms (immediate tunnel availability via fast-start candidates).
  • Background Query Rate: ~1.89 QPS (well below the 15 QPS budget).
  • Throughput: ~137 KiB/s sustained payload over each active paths.

Verification

  • go test ./... passes across all packages.
  • Zero major CodeRabbit / linter findings.

@taskkillstar

taskkillstar commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor Author

Minimizes startup time (no need to scan the entire resolvers list), allows to have several hundreds of resolvers in the list without sacrificing connection time.

Requested by FR #179

@salehMomtaz

Copy link
Copy Markdown

@masterking32 these precious times are passing by and the complete internet blackout resistance projects were not developed since filternet came back. i hope you do not abandon this project.

@salehMomtaz

Copy link
Copy Markdown

@Mygod @masterking32 attention needed

@taskkillstar

Copy link
Copy Markdown
Contributor Author

@salehMomtaz
You can try my fork which already has this feature and more. Read the full description at the top of Readme.md and download the client for your platform from Releases page (https://github.com/taskkillstar/MasterDnsVPN/releases/tag/fork-v1.0.0)

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot review overview

🟡 Changes recommended

Resolver qualification, concurrency, persistence, and configuration-contract defects can activate rejected resolvers or produce incorrect rankings.

Review effort: Balanced
Findings: 3 High severity · 7 Medium severity · 7 Low severity

Open (17)
What changed in this PR

Introduces FastStart resolver discovery, micro-burst qualification, ranked resolver persistence, and live runtime statistics.

Changes:

  • Starts after validating a minimal resolver set and rechecks others asynchronously.
  • Adds resolver scoring, active-pool limits, burst testing, and ranked persistence.
  • Expands tests, configuration, and multilingual documentation.
File Description
.gitignore Adds generated/runtime exclusions.
README.MD Documents new CLI and resolver features.
README_ZH.MD Updates Chinese documentation.
README_RU.MD Updates Russian documentation.
README_IT.MD Updates Italian documentation.
README_FA.MD Updates Persian documentation.
README_ES.MD Updates Spanish documentation.
client_config.toml.simple Adds burst, ranking, and stats settings.
client_resolvers.simple Documents managed resolver ranking.
internal/​config/​client.go Adds and validates client settings.
internal/​config/​client_test.go Tests new configuration fields.
internal/​config/​client_resolvers.go Preserves order and writes ranked blocks.
internal/​config/​client_resolvers_test.go Tests ordering and persistence.
internal/​config/​server.go Exports default server configuration.
internal/​udpserver/​server.go Exports packet handling for tests.
internal/​client/​async_runtime.go Persists rankings during shutdown.
internal/​client/​balancer.go Adds pool limits, scoring, and optimization.
internal/​client/​balancer_test.go Tests pool selection and ranking.
internal/​client/​client.go Starts stats monitoring and configures limits.
internal/​client/​client_utils.go Saves rankings and improves banner output.
internal/​client/​fast_start_test.go Tests FastStart behavior.
internal/​client/​micro_burst.go Implements burst qualification.
internal/​client/​micro_burst_test.go Tests burst probing and selection.
internal/​client/​mtu.go Implements early MTU-test completion.
internal/​client/​mtu_logging.go Adds qualification and reactivation logs.
internal/​client/​runtime_stats.go Implements runtime monitoring.
internal/​client/​runtime_stats_test.go Tests runtime statistics and persistence.
internal/​client/​score.go Adds resolver scoring utilities.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread internal/client/balancer.go Resolved
Comment thread internal/client/micro_burst.go Resolved
Comment thread internal/config/client_resolvers.go Resolved
Comment thread internal/client/client.go Resolved
Comment thread internal/client/micro_burst.go Resolved
Comment thread README_FA.MD Resolved
Comment thread README_IT.MD Resolved
Comment thread README_IT.MD Resolved
Comment thread README_RU.MD Resolved
Comment thread README_ZH.MD Resolved
taskkillstar pushed a commit to taskkillstar/MasterDnsVPN that referenced this pull request Oct 11, 2026

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

Startup can overlook usable resolvers, and pool optimization can reactivate rejected or MTU-incompatible candidates.

10 open issues
4 previously missed issues

In code that hasn't changed since last review

Medium severity Apply resolver capacity limits after MTU burst qualification

internal/​client/​balancer.go:1379

This cap also applies during ApplyMTUProbeResult, before burst qualification. RunInitialMTUTests then qualifies only ActiveConnections(), excluding MTU-passing candidates placed on standby here. With MAX_ACTIVE_RESOLVERS=1 and FastStart disabled, a low-latency but rate-limited resolver can exclude a usable alternative, fail the burst test, and prevent startup despite a full MTU scan. Keep all MTU-passing candidates eligible for qualification, and apply the capacity limit after burst ranking.

Medium severity Limit test parallelism to make cancellation assertions deterministic

internal/​client/​fast_start_test.go:90

The default MTUTestParallelism=16 allows all ten mock resolvers to run at once. All ten can commit successful results before cancellation is observed, making the later activeCount < 10 assertion fail under valid scheduling. Set parallelism to two so reaching the target necessarily leaves some endpoints untested.

Medium severity Timestamp MTU responses while the packet train is sent

internal/​client/​micro_burst.go:184

Responses are read only after the entire paced send loop finishes, so this timestamp includes time already-arrived packets spent queued locally. With 32 packets spaced 2 ms apart, an immediate reply to the first query is measured roughly 62 ms late. These inflated round-trip times seed the balancer and affect ranking and promotion. Receive and timestamp responses while sending the train, synchronizing access to the per-query timing state.

Medium severity Use monotonic traffic totals for periodic report gating

internal/​client/​runtime_stats.go:247

calculateTotalSentPackets sums adaptive scoring counters, not monotonic traffic totals: connectionStats.applyHalfLife halves them above 1,000 observations, and health rechecks can reseed them. After a decrease, this comparison suppresses periodic reports until the previous high-water mark is exceeded, potentially indefinitely despite ongoing traffic. Use a monotonic traffic counter or an interval activity flag for this gate instead of the decaying statistics.

10 resolved since last review

Review effort: Balanced

Comment thread internal/client/balancer.go Resolved
Comment thread internal/client/mtu.go Resolved
Comment thread internal/client/mtu.go Resolved
taskkillstar pushed a commit to taskkillstar/MasterDnsVPN that referenced this pull request Oct 30, 2026
@masterking32
masterking32 requested a balanced review from Copilot October 30, 2026 11:38

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Comment thread internal/client/micro_burst.go Resolved
Comment thread internal/client/mtu.go Resolved
Comment thread internal/client/mtu.go Resolved
Comment thread internal/config/client_resolvers.go Resolved
Comment thread internal/client/micro_burst.go Resolved
Comment thread internal/client/mtu.go Resolved
Comment thread internal/client/runtime_stats.go Outdated
Comment on lines +245 to +247
currentSentTotal := c.calculateTotalSentPackets()
if currentSentTotal > lastSentTotal {
lastSentTotal = currentSentTotal
taskkillstar pushed a commit to taskkillstar/MasterDnsVPN that referenced this pull request Oct 30, 2026
taskkillstar pushed a commit to taskkillstar/MasterDnsVPN that referenced this pull request Oct 30, 2026
@masterking32
masterking32 requested a max review from Copilot November 1, 2026 00:19

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

Unresolved critical defects in resolver qualification and pool management can discard healthy connections, admit failing endpoints, and cause startup failures or persistent disconnections.

21 open issues

And 1 more that still need to be addressed.

6 resolved since last review

Review effort: Max

Comment thread internal/client/balancer.go Outdated
Comment on lines +1434 to +1438
_, score := CalculateResolverScore(downloadMTU, avgRTT, lossRatio)
if score <= 0 {
return 1.0
}
return score
Comment thread internal/client/balancer.go Outdated
Comment on lines +1480 to +1484
demotedConn := &b.connections[worstActiveIdx]
demotedConn.IsValid = false
demotedConn.StandbyEligible = true
b.activeIDs[worstActivePos] = idx // Replace in activeIDs slice
b.addInactiveIndexLocked(worstActiveIdx)
Comment thread internal/client/balancer.go Outdated
Comment on lines +1529 to +1533
if b.maxActiveResolvers <= 0 || len(b.activeIDs) == 0 || len(b.inactiveIDs) == 0 {
return false
}

swapped := false
Comment thread internal/client/micro_burst.go Outdated

now := time.Now()
packet, err := DnsParser.ExtractVPNResponse(readBuf[:n], useBase64Flag)
if err != nil || packet.PacketType != Enums.PACKET_MTU_DOWN_RES || len(packet.Payload) < mtuProbeCodeLength {
Comment thread internal/client/micro_burst.go Outdated
Comment on lines +379 to +387
burstResult := c.sendPipelinedMicroBurst(
ctx,
conn,
transport,
packetCount,
c.syncedDownloadMTU,
c.syncedUploadMTU,
timeout,
)
Comment on lines +110 to +112
// UpdateResolversFileWithRanked updates or prepends the auto-ranked best resolvers block
// at the top of the resolvers file while preserving all custom lines, comments, and subnets below.
func UpdateResolversFileWithRanked(filePath string, ranked []ResolverAddress) error {
Comment thread internal/client/balancer.go Outdated
Comment on lines +468 to +478
// Only consider connections that have passed MTU discovery or are active or have stats
hasStats := false
if i < len(b.stats) && b.stats[i] != nil {
sent, _, _, _, rttCount := b.stats[i].snapshot()
if sent > 0 || rttCount > 0 {
hasStats = true
}
}
if !conn.IsValid && conn.UploadMTUBytes <= 0 && conn.DownloadMTUBytes <= 0 && !hasStats {
continue
}
if err != nil {
t.Fatalf("client codec init failed: %v", err)
}
client := New(cfg, nil, codec)
Comment thread internal/client/mtu_logging.go Outdated
status = "<red>REJECTED</red>"
}

speedStr := fmt.Sprintf("%.1f KB/s", r.BurstResult.ThroughputKBps)
Comment thread internal/client/runtime_stats.go Outdated

c.log.Infof("%s", separator)
c.log.Infof(
"<blue>Total Tunnel Traffic: Sent <cyan>%d</cyan> pkts | Acked <green>%d</green> | Lost <yellow>%d</yellow> (<yellow>%.1f%%</yellow>) | Active Streams: <cyan>%d</cyan></blue>",
taskkillstar pushed a commit to taskkillstar/MasterDnsVPN that referenced this pull request Nov 1, 2026
…management, qualification, stats, and docs
@masterking32

Copy link
Copy Markdown
Owner

Please ping me once you've resolved the conflicts and finalized the PR. Thank you!

@taskkillstar
taskkillstar marked this pull request as draft November 3, 2026 16:51
taskkillstar pushed a commit to taskkillstar/MasterDnsVPN that referenced this pull request Nov 5, 2026
taskkillstar pushed a commit to taskkillstar/MasterDnsVPN that referenced this pull request Nov 5, 2026
taskkillstar pushed a commit to taskkillstar/MasterDnsVPN that referenced this pull request Nov 5, 2026
taskkillstar pushed a commit to taskkillstar/MasterDnsVPN that referenced this pull request Nov 5, 2026
…management, qualification, stats, and docs
@taskkillstar
taskkillstar force-pushed the feat/fast-start-resolvers branch from 8615f90 to 1c718dd Compare November 5, 2026 19:05
@masterking32

Copy link
Copy Markdown
Owner

I reviewed the latest head, including the earlier feedback and the final fork merge.

Many earlier issues are fixed in the main startup and health-check paths: cancellation, endpoint diversity, burst failure handling, standby recovery, file safety, user edits, and stats handling.

However, the final merge adds a separate background discovery path that bypasses those fixes:

  1. background_discovery.go activates MTU results without burst qualification or checking leases, and ignores the shared query budget. In a loopback test, it replaced a healthy active path with one that received 0/4 burst responses, even with both burst settings enabled.

  2. Newly detected local endpoints are never registered in the pool. The update calls return false for unknown keys, but the code still logs them as verified.

  3. Scan mode reports that new endpoints were saved, while the ranked-file writer filters them out because they are absent from the user section. Please keep that protection for automatic ranking and give explicit scan apply a separate way to add new entries.

  4. The scanner only checks Domains[0]. I reproduced a case where normal startup works through the second domain, but the scanner finds no healthy resolvers.

Please also remove the fork-only changes from the final merge: deleted translations, fork branding, fork-v release defaults, and the upstream-sync workflow.

The existing tests, builds, vet, and client/config race tests passed. Three added loopback regression tests reproduced issues 1, 3, and 4 twice. The integration test should also cover Client. Run, default-enabled background discovery, and session resets.

I would keep this in draft until these issues are fixed.

@taskkillstar
taskkillstar force-pushed the feat/fast-start-resolvers branch from 1c718dd to a54a900 Compare November 7, 2026 12:18
@taskkillstar

Copy link
Copy Markdown
Contributor Author

Hi, @masterking32
Thank you for the review.
The merge was accidental and introduced all 4 bugs you mentioned above. I rolled it back.
I am finishing my internal tests and code reviews before I submit this PR for your review again. I'm sorry for wasting your Copilot tokens earlier, I try to do a better testing job this time.
I'll notify you when this PR will be ready.

…ver CLI aliases

- Support auto-saving ranked resolvers, configurable micro-burst parameters, and auto-disable timeout settings.
- Add CLI flag aliases (-c, -l, -v) to server binary.
- Ensure UDP server session cleanup is initialized on creation.
…asynchronous discovery

- Introduce authoritative ResolverPool decoupling path state, distinct endpoint quotas, and candidate lifecycle (Checking, Active, Standby, Ineligible) from packet balancing.
- Add asynchronous ResolverDiscoveryEngine with token-bucket BackgroundQueryLimiter for rate-limited background probing.
- Implement pipelined micro-burst qualification and MTU discovery.
- Add asynchronous RankedPersistenceWriter with MinWriteInterval pacing to prevent disk thrashing.
- Unify path scoring formula with loss weighting, latency penalization, and margin replacement.
- Add live runtime performance stats inspection and graceful connection failover.
…t suites

- Add end-to-end acceptance benchmark harness verifying readiness, background query rate, and throughput.
- Add lifecycle, policy, distinct endpoint diversity, and displacement unit tests.
- Add adversarial concurrency and stress tests verifying thread-safety and race freedom.
- Add synctest-based tests for asynchronous ranked writer scheduling and timer intervals.
- Align multi-lingual READMEs with canonical domain terminology (Active Paths, preferred path, Tunnel Paths).
- Document testing infrastructure and test acceptance standards in TEST_INFRA.md and TEST_READY.md.
- Update sample client configuration with ranked auto-save and micro-burst tuning parameters.
- Add ignore patterns for local scratch and agent artifacts in .gitignore.
@taskkillstar
taskkillstar force-pushed the feat/fast-start-resolvers branch from 6b49427 to ea17936 Compare November 8, 2026 11:35
@taskkillstar taskkillstar changed the title feat(client): implement FastStart for early connection and background resolver discovery feat(client): implement FastStart for quick connection, background resolver discovery and scoring, autonomous multi-resolver pool lifecycle. Nov 8, 2026
@taskkillstar

Copy link
Copy Markdown
Contributor Author

Hi @masterking32,

As this pull request matured, it addressed the underlying architectural requirements of resolver pool lifecycle, background rate-limited discovery, and persistent caching beyond the initial FastStart prototype.

To make the final review straightforward, I have:

  • Squashed and organized the 42 iterative review commits into 4 clean, logically grouped commits (Config/CLI, Core Pool & Discovery Engine, Test Suites, and Documentation).
  • Updated the PR title and description to reflect the full architectural scope and included acceptance benchmark metrics.
  • Verified that all review feedback has been addressed with 100% passing test suites and zero linter warnings.

It's ready for your review.

@taskkillstar
taskkillstar marked this pull request as ready for review November 8, 2026 11:47
@taskkillstar

taskkillstar commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi @masterking32 ,

Please review this PR when you'll have a minute.

Thanks!

@masterking32

Copy link
Copy Markdown
Owner

Looks good now.
Thank you.

@masterking32
masterking32 merged commit 4df3232 into masterking32:main Nov 14, 2026
1 check passed
@taskkillstar
taskkillstar deleted the feat/fast-start-resolvers branch November 16, 2026 13:12
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.

6 participants