java.lang.Object
net.i2p.router.Tuner.BaseParam
All Implemented Interfaces:
Tuner.TunableParam
Direct Known Subclasses:
Tuner.AckFrequencyParam, Tuner.ActivityWindowParam, Tuner.BuildFirstHopTimeoutParam, Tuner.BuildHandlerMaxQueueParam, Tuner.BuildHandlerThreadsParam, Tuner.BuildRequestTimeoutParam, Tuner.CodelIntervalParam, Tuner.CodelTargetParam, Tuner.ConcurrencyThrottleThresholdParam, Tuner.CongestionAvoidanceGrowthParam, Tuner.ConnectTimeoutMultiplierParam, Tuner.DataMessageTimeoutParam, Tuner.EDHPreCalcMinParam, Tuner.ExploreBredthParam, Tuner.FirstHopFailureCooldownParam, Tuner.FirstHopFailureThresholdParam, Tuner.GoodDeficitThrottleParam, Tuner.HandlerThreadPriorityParam, Tuner.I2PTunnelClientMaxConnectionsParam, Tuner.I2PTunnelClientRunnerMaxParam, Tuner.I2PTunnelServerBacklogParam, Tuner.I2PTunnelServerHandlerThreadsParam, Tuner.I2PTunnelServerIOStallTimeoutParam, Tuner.I2PTunnelServerIOTransferParam, Tuner.I2PTunnelServerThreadsParam, Tuner.IbEstablishTimeParam, Tuner.IbMsgsPerPumpParam, Tuner.ImmediateAckDelayParam, Tuner.InactivityTimeoutParam, Tuner.InitConcurrentMsgsParam, Tuner.InitialAckDelayParam, Tuner.InitialResendDelayParam, Tuner.InitialRTOParam, Tuner.InitialWindowSizeParam, Tuner.InitRTOParam, Tuner.InternalQueueSizeParam, Tuner.LeaseResendCountParam, Tuner.LookupLimitParam, Tuner.LossyThresholdParam, Tuner.LsLookupTimeoutParam, Tuner.MaxConcurrentBuildsParam, Tuner.MaxConcurrentEstablishParam, Tuner.MaxConcurrentMessagesParam, Tuner.MaxDispatchAgeParam, Tuner.MaxFastPeersParam, Tuner.MaxHighCapPeersParam, Tuner.MaxInboundBufferParam, Tuner.MaxParticipatingTunnelsParam, Tuner.MaxProfilesParam, Tuner.MaxQueuedOutboundParam, Tuner.MaxResendDelayParam, Tuner.MaxRetransmissionsParam, Tuner.MaxRTOParam, Tuner.MaxRttParam, Tuner.MaxSendWindowParam, Tuner.MaxSlowStartWindowParam, Tuner.MaxStreamsParam, Tuner.MaxSynResendsParam, Tuner.MaxWindowSizeParam, Tuner.MaxWriteBufsParam, Tuner.MessageProcessingThrottleParam, Tuner.MinConcurrentMsgsParam, Tuner.MinFastPeersParam, Tuner.MinHighCapPeersParam, Tuner.MinPacingRateParam, Tuner.MinResendDelayParam, Tuner.MinRTOParam, Tuner.MLKEMPreCalcMinParam, Tuner.NetDBMaxConcurrentParam, Tuner.NetDBMaxSearchTimeParam, Tuner.NetDBSearchLimitParam, Tuner.NetDBSingleSearchTimeParam, Tuner.NtcpEstablishTimeParam, Tuner.NtcpFailsafeFreqParam, Tuner.NTCPQueueCapacityParam, Tuner.NtcpReaderThreadsParam, Tuner.NtcpSendFinisherThreadsParam, Tuner.NtcpWriterThreadsParam, Tuner.ObEstablishTimeParam, Tuner.ObMsgsPerPumpParam, Tuner.OutboundMsgExpirationParam, Tuner.ParticipatingThrottleMaxParam, Tuner.ParticipatingThrottleMinParam, Tuner.ParticipatingThrottlePctParam, Tuner.PassiveFlushDelayParam, Tuner.PeerOutboundQueueParam, Tuner.PercentLookupLimitParam, Tuner.PerTunnelBweDivisorParam, Tuner.PoolBackoffMsParam, Tuner.PoolFailureThresholdParam, Tuner.PostRTOWindowParam, Tuner.PumperIdleLpsParam, Tuner.PumperQueueCapacityParam, Tuner.PumperThreadsParam, Tuner.RdnsPoolSizeParam, Tuner.REDMaxDropProbParam, Tuner.REDMaxThresholdParam, Tuner.REDMinThresholdParam, Tuner.ReplenishFrequencyParam, Tuner.RequestHighLoadCpuParam, Tuner.RequestHighLoadLagParam, Tuner.RequestLoadWeightParam, Tuner.RequestModerateLoadCpuParam, Tuner.RequestModerateLoadLagParam, Tuner.RequestRejectSteepnessParam, Tuner.RequestRejectThresholdParam, Tuner.RequestSustainedModerateLoadParam, Tuner.RequestThrottleBurstParam, Tuner.RequestThrottleMaxParam, Tuner.RequestThrottleMinParam, Tuner.RequestThrottlePctParam, Tuner.RequeueTimeParam, Tuner.ResendTimeoutParam, Tuner.RiLookupTimeoutParam, Tuner.RTOMultiplierParam, Tuner.SelectorLoopDelayParam, Tuner.SendPoolCapacityParam, Tuner.SentMessagesCleanTimeParam, Tuner.SlowStartGrowthParam, Tuner.SocketConnectTimeoutParam, Tuner.StaleBuildThresholdParam, Tuner.StreamingReceiveWorkersParam, Tuner.TestJobMaxDelayParam, Tuner.TestJobMaxPeriodParam, Tuner.TestJobMaxQueuedParam, Tuner.TestJobMinDelayParam, Tuner.TestJobMinPeriodParam, Tuner.ThrottleRejectExponentParam, Tuner.TimerThreadsParam, Tuner.TransitLoadWeightParam, Tuner.TransitRejectSteepnessParam, Tuner.TransitRejectThresholdParam, Tuner.TransitThrottleFactorParam, Tuner.TunnelGrowthFactorParam, Tuner.TunnelIVFilterMParam, Tuner.TunnelTargetBufferParam, Tuner.UDPHandlerThreadsParam, Tuner.UdpMaxRtoParam, Tuner.UDPMessageReceiverThreadsParam, Tuner.UntestedMultiplierParam, Tuner.WestwoodDecayFactorParam, Tuner.WriterQueueSizeParam, Tuner.XDHPreCalcMinParam
Enclosing class:
Tuner

abstract static class Tuner.BaseParamextends Object implements Tuner.TunableParam
Base class for tunable params with history tracking and auto-revert.

Each param wraps a single router configuration value. The tuning loop reads an observed stat, computes a target, and applies it:

observed = getObservedStat()
target   = computeTarget(observed)
target   = clamp(target, min, max)
target   = dampenByHealth(target, current)
target   = accelerateRollback(target, current, defaultValue)
applyValue(target)

Min/max/step ranges are stored in autotune.config and can be changed at runtime via the console UI (no restart needed). Factory defaults are captured on first run and persisted for auto-revert when system health is degraded.

Thread safety: all fields are accessed only from the Tuner timer thread, except _override and _autoTuning which are set from the console form handler.

  • Field Details

    • sharedAutotune

      static volatile Tuner.AutotuneConfig sharedAutotune
      Shared instance — set once in Tuner constructor, used by all BaseParams.
    • _name

      protected final String _name
      Internal config property key (e.g. "i2p.tunnel.socketConnectTimeout").
    • _description

      protected final String _description
      Human-readable label for display in the Tuner UI.
    • _subsystem

      protected final String _subsystem
      Subsystem identifier this parameter belongs to.
    • _propPrefix

      protected final String _propPrefix
      Config key prefix for property lookups.
    • _keyMin

      private final String _keyMin
      Autotune.config keys for this param's range and persisted state. Built once because the name is final while the range refresh runs every cycle.
    • _keyMax

      private final String _keyMax
      Config key the tuned maximum is stored under.
    • _keyStep

      private final String _keyStep
      Config key the tuned step is stored under.
    • _keyValue

      private final String _keyValue
      Config key the tuned value is stored under.
    • _keyDefault

      private final String _keyDefault
      Config key the original default is remembered under.
    • _defaultMin

      protected final int _defaultMin
      Default minimum value from code or config.
    • _defaultMax

      protected final int _defaultMax
      Default maximum value from code or config.
    • _defaultStep

      protected final int _defaultStep
      Default step/increment size for adjustments.
    • _min

      protected int _min
      Current minimum value (may differ from default after tuning).
    • _max

      protected int _max
      Current maximum value (may differ from default after tuning).
    • _effMax

      protected int _effMax
      Effective ceiling = min(_max, memory-derived bound); never exceeds _max.
    • _step

      protected int _step
      Current step/increment size (may differ from default).
    • _statName

      protected final String _statName
      Router stat name for observed value feedback.
    • _defaultValue

      protected int _defaultValue
      Factory default: value before any tuning. Persisted on first run for auto-revert.
    • _factoryDefault

      protected final int _factoryDefault
      Code-level default captured at construction time. Used by Tuner.restoreDefaults().
    • _initialValue

      protected final int _initialValue
      Last known value (from persistence or runtime default). Used as tuning baseline.
    • _firstTick

      protected boolean _firstTick
      True until first update() call — applies persisted value from autotune.config.
    • _staleDefaultLogged

      private boolean _staleDefaultLogged
      True once a stale persisted default has been reported, so the permanent condition is logged at DEBUG exactly once per param instead of on every tuning cycle.
    • _override

      protected volatile int _override
      User-set override value, or Integer.MIN_VALUE if unset.
    • _autoTuning

      protected volatile boolean _autoTuning
      Whether autotuning is active for this parameter.
    • _health

      protected Tuner.SystemHealth _health
      Health score and subsystem for autotune decisions.
    • _lastAppliedTarget

      private int _lastAppliedTarget
      The target most recently applied, or 0 when the last take effect. Used to tell a param that is genuinely moving from one that is stuck retrying the same value.
    • _noEffectReported

      private boolean _noEffectReported
      Whether an ineffective apply has already been reported for this param, so it is logged once instead of on every tuning cycle.
    • _cpuDriven

      protected boolean _cpuDriven
      Whether this param's value is being driven by CPU load rather than its own stat.
    • _valueHistory

      protected final int[] _valueHistory
      Rolling window of recent tunable values for trend analysis.
    • _statHistory

      protected final double[] _statHistory
      Rolling window of recent stat values for trend analysis.
    • _historyCount

      protected int _historyCount
      Number of valid entries in _valueHistory / _statHistory.
    • _log

      protected final Log _log
      Class logger.
    • _ctx

      protected final RouterContext _ctx
      Router context.
    • _autotune

      protected final Tuner.AutotuneConfig _autotune
      Autotune profile for this tunable parameter.
    • DEGRADED_THRESHOLD

      private static final double DEGRADED_THRESHOLD
      Health score below which the tuner reverts its changes.
      See Also:
    • _reverted

      private boolean _reverted
      True once the tuner has reverted to defaults.
    • _clampWarned

      private boolean _clampWarned
      Whether the clamp warning was already emitted for this target.
  • Constructor Details

    • BaseParam

      protected BaseParam(String name, String description, String subsystem, int defaultMin, int defaultMax, int defaultStep, String statName, RouterContext ctx)
      A tunable parameter with the given name, description and subsystem.
      Parameters:
      name - internal property key (e.g. "i2p.tunnel.socketConnectTimeout")
      description - human-readable label shown in Tuner UI (e.g. "Socket connect timeout (ms)") — keep short, include unit in parens; same convention for all new params
      subsystem - subsystem identifier (e.g. "i2ptunnel", "streaming")
      defaultMin - minimum allowed value
      defaultMax - maximum allowed value
      defaultStep - tuning step size
      statName - router stat name for observed feedback
      ctx - router context; dereferenced here, so it must not be null
    • BaseParam

      protected BaseParam(String name, String description, String subsystem, int defaultMin, int defaultMax, int defaultStep, String statName, RouterContext ctx, Tuner.AutotuneConfig autotune)
      A tunable parameter with the given name, description and subsystem.
      Parameters:
      name - internal property key
      description - human-readable label shown in Tuner UI
      subsystem - subsystem identifier (e.g. "i2ptunnel", "streaming")
      defaultMin - minimum allowed value
      defaultMax - maximum allowed value
      defaultStep - tuning step size
      statName - router stat name for observed feedback
      ctx - router context; dereferenced here, so it must not be null
      autotune - autotune config, or null for shared
    • BaseParam

      protected BaseParam(String name, String description, String subsystem, int defaultMin, int defaultMax, int defaultStep, String statName, RouterContext ctx, Tuner.AutotuneConfig autotune, int defaultValue)
      A tunable parameter with the given name, description and subsystem.

      The defaultValue is the code-level default for this parameter. It is captured as _factoryDefault and used as the authoritative source of truth for auto-revert decisions, so that stale persisted values from previous Tuner versions cannot corrupt the tuning baseline. If defaultValue is zero or negative, falls back to getRuntimeValue().

      Parameters:
      name - internal property key
      description - human-readable label shown in Tuner UI
      subsystem - subsystem identifier (e.g. "i2ptunnel", "streaming")
      defaultMin - minimum allowed value
      defaultMax - maximum allowed value
      defaultStep - tuning step size
      statName - router stat name for observed feedback
      ctx - router context; dereferenced here, so it must not be null
      autotune - autotune config, or null for shared
      defaultValue - the code-level default value, or 0 to use runtime default
  • Method Details

    • getName

      public String getName()
      Param name.
      Specified by:
      getName in interface Tuner.TunableParam
      Returns:
      the internal property key this param is registered under, which also forms the prefix of its min, max, step, value, and default properties
    • getDescription

      public String getDescription()
      Param description.
      Specified by:
      getDescription in interface Tuner.TunableParam
      Returns:
      the label the tuning page renders for this param
    • getSubsystem

      public String getSubsystem()
      Subsystem name.
      Specified by:
      getSubsystem in interface Tuner.TunableParam
      Returns:
      the SUB_* group this param is scored under
    • getMin

      public int getMin()
      Minimum value.
      Specified by:
      getMin in interface Tuner.TunableParam
      Returns:
      the live lower bound, after autotune.config overrides
    • getMax

      public int getMax()
      Maximum value.
      Specified by:
      getMax in interface Tuner.TunableParam
      Returns:
      the live upper bound, after autotune.config overrides
    • getStep

      public int getStep()
      Step size.
      Specified by:
      getStep in interface Tuner.TunableParam
      Returns:
      the live increment, after autotune.config overrides
    • getDefaultValue

      public int getDefaultValue()
      Default value.
      Returns:
      the value before any tuning
    • isAutoTuning

      public boolean isAutoTuning()
      Whether auto-tuning is enabled.
      Specified by:
      isAutoTuning in interface Tuner.TunableParam
      Returns:
      true if auto-tuning is enabled
    • getShareBps

      protected static int getShareBps(RouterContext ctx)
      Current share bandwidth in bytes per second. Useful for params whose ranges should scale with bandwidth.
      Parameters:
      ctx - router context supplying the configured share bandwidth
      Returns:
      the share bps
    • getDefaultMin

      protected int getDefaultMin(RouterContext ctx)
      Effective default min — override for bandwidth-scaled params. Called by refreshRanges(RouterContext) instead of _defaultMin.
      Parameters:
      ctx - router context passed by refreshRanges, for bandwidth-scaled overrides
      Returns:
      the default min
    • getDefaultMax

      protected int getDefaultMax(RouterContext ctx)
      Effective default max — override for bandwidth-scaled params. Called by refreshRanges() instead of _defaultMax.
      Parameters:
      ctx - router context passed by refreshRanges, for bandwidth-scaled overrides
      Returns:
      the default max
    • getHeavyTransitThreshold

      protected static int getHeavyTransitThreshold(RouterContext ctx)
      Transit bandwidth threshold for "heavy" — 80% of configured share bandwidth. Replaces the old hardcoded 50 KB/s which was far too low for any real router.
      Parameters:
      ctx - router context supplying the configured share bandwidth
      Returns:
      the heavy transit threshold
    • getSustainedHeavyTransitThreshold

      protected static int getSustainedHeavyTransitThreshold(RouterContext ctx)
      Transit bandwidth threshold for "sustained heavy" — 50% of configured share.
      Parameters:
      ctx - router context supplying the configured share bandwidth
      Returns:
      the sustained heavy transit threshold
    • getDefaultStep

      protected int getDefaultStep(RouterContext ctx)
      Effective default step — override for bandwidth-scaled params. Called by refreshRanges() instead of _defaultStep.
      Parameters:
      ctx - router context passed by refreshRanges, for bandwidth-scaled overrides
      Returns:
      the default step
    • refreshRanges

      public void refreshRanges(RouterContext ctx)
      Re-read min/max/step from autotune.config — live update, no restart.

      Called once per tuning cycle before computeTarget(). Clamps loaded ranges to constructor limits to prevent stale config values from exceeding actual setter limits. Also clamps the persisted value to the new range if it was set before a code change lowered the max.

      Parameters:
      ctx - router context, forwarded to the range overrides below
    • refreshDefault

      public void refreshDefault(RouterContext ctx)
      Re-read the default value from autotune.config for live updates.

      Called once per tuning cycle. When a user saves a new default via the console form, this method picks it up and uses it as the auto-revert target. If the persisted default differs from the factory default (code-level default), it is treated as stale and ignored. The factory default is the authoritative source of truth.

      A stale default is a persistent config state, not a recurring event: it stays in autotune.config until edited, so re-announcing it every cycle produced thousands of identical WARN lines for a condition the code already handles correctly. It is therefore reported once per param at DEBUG, and WARN stays free for things that actually need attention.

      Parameters:
      ctx - router context, unused here; kept for symmetry with refreshRanges
    • persistValue

      protected void persistValue(RouterContext ctx, int value)
      Persist a tuned value to autotune.config.

      Writes are throttled: the value is marked dirty and flushed to disk at most once per 5 minutes by Tuner.AutotuneConfig.save(). This avoids excessive I/O from params that change every cycle.

      Parameters:
      ctx - the router context
      value - the new value to persist
    • setOverride

      public void setOverride(int value)
      A manual override value. Disables auto-tuning until cleared.

      Called from the console form handler when a user manually sets a param value. Setting value < 0 re-enables auto-tuning. The override is applied immediately via applyValue(int) and persisted to autotune.config.

      Specified by:
      setOverride in interface Tuner.TunableParam
      Parameters:
      value - the override value, or < 0 to re-enable auto-tuning
    • setHealth

      void setHealth(Tuner.SystemHealth health)
      The current system health score for this update cycle.
      Parameters:
      health - health snapshot computed by the tuner
    • getValueHistory

      public int[] getValueHistory()
      Rolling window of recent tunable values.
      Specified by:
      getValueHistory in interface Tuner.TunableParam
      Returns:
      the values, oldest first
    • getStatHistory

      public double[] getStatHistory()
      Rolling window of recent stat values.
      Specified by:
      getStatHistory in interface Tuner.TunableParam
      Returns:
      the stat values, oldest first
    • snapshot

      public Tuner.ParamSnapshot snapshot()
      Capture snapshot of current tunable state for display.
      Specified by:
      snapshot in interface Tuner.TunableParam
      Returns:
      the snapshot for display
    • applyValue

      protected abstract void applyValue(int value)
      Apply the tunable value to the router configuration.
      Parameters:
      value - the tunable value to apply to router configuration
    • getRuntimeValue

      protected abstract int getRuntimeValue()
      Current runtime value read from the router configuration.
      Returns:
      current runtime value read from router config
    • getObservedStat

      protected abstract double getObservedStat(RouterContext ctx)
      Observed stat value used for autotuning.

      ctx is always this param's own context: Tuner takes a single RouterContext, hands the same instance to every BaseParam constructor, and both call sites pass _ctx. It was previously passed as null, which silently broke any implementation that used the argument instead of the field — a param reading a cross-reference stat then threw on every tuning cycle, was caught by the cycle handler, and never tuned at all, with nothing but a repeated WARN to show for it. Implementations may use either ctx or _ctx; both are the same object.

      Parameters:
      ctx - router context, never null
      Returns:
      observed stat value for autotuning
    • computeTarget

      protected abstract int computeTarget(double observed)
      Target tunable value computed from the observed stat.
      Parameters:
      observed - current stat value
      Returns:
      target tunable value
    • getAdditionalStat

      protected double getAdditionalStat(RouterContext ctx, String statName)
      Fetch an additional stat value for cross-reference decisions.

      Cross-reference stats are used alongside the primary stat to make more informed tuning decisions. For example, a streaming param might use transport.sendProcessingTime as its primary signal but also check jobQueue.jobLag to avoid increasing load when the CPU is already saturated.

      Parameters:
      ctx - the router context
      statName - the stat to query (e.g. "jobQueue.jobLag")
      Returns:
      the 60s rolling average, or NaN if not available
    • getAdditionalStatHourly

      protected double getAdditionalStatHourly(RouterContext ctx, String statName)
      Fetch an additional stat value using the 1-hour average.

      Useful for less time-sensitive decisions where we want to confirm a trend rather than react to a short-term spike. For example, build success rate should be checked over an hour to avoid over-reacting to a brief network glitch.

      Parameters:
      ctx - the router context
      statName - the stat to query
      Returns:
      the 1-hour rolling average, or NaN if not available
    • getAdditionalStatLong

      protected double getAdditionalStatLong(RouterContext ctx, String statName)
      Fetch an additional stat value using the 10-minute average.

      The 10-minute period is a medium-term signal. Slower to react than the 60s period but less prone to gaps from brief idle windows. Use this as the first fallback when the 60s stat has no recent events, since most streaming stats are registered with both ONE_MINUTE and TEN_MINUTES rates.

      Parameters:
      ctx - the router context
      statName - the stat to query
      Returns:
      the 10-minute rolling average, or NaN if not available
    • getAdditionalEventCount

      protected double getAdditionalEventCount(RouterContext ctx, String statName)
      Fetch the event count for an additional stat using the 60s period.

      For event-count stats where addRateData(name, 1) is called, getAdditionalStat(RouterContext, String) returns getAverageValue() which is always 1.0 when events exist. This method returns the raw event count instead, which is the correct metric for "how many events occurred".

      Parameters:
      ctx - the router context
      statName - the stat to query
      Returns:
      the event count in the last 60s, or NaN if not available
    • getStatPeriodStamp

      protected double getStatPeriodStamp(RouterContext ctx, String statName)
      When the window behind a stat's event count last completed, in ms, or NaN when it cannot be determined.

      A coalesced Rate stamps the wall clock of every coalesce, and coalescing is what closes a period, so this advances exactly once per window. It is the identity of the window, which is what a caller needs to tell "a new reading exists" from "the same reading as last cycle".

      The event count itself cannot serve: two periods can carry identical counts, an idle period repeats (0, 0) forever, and a count of zero means the ratio is undefined rather than low. Any of those reads as "unchanged" and freezes a decision that depends on it.

      Parameters:
      ctx - the router context
      statName - the stat to query
      Returns:
      the last coalesce time in ms, or NaN
    • signalIsFresh

      static boolean signalIsFresh(double periodStamp, double lastStamp)
      Whether a signal reading is from a window that closed since the stored stamp. Pure, so the gate can be pinned without a router.
      Parameters:
      periodStamp - the current window's close time, or NaN
      lastStamp - the close time this decision was last taken on, or NaN
      Returns:
      true when the reading is new enough to act on; an unknown stamp returns true so an unreadable signal falls back to the prior behaviour rather than freezing the param
    • getAdditionalStat5Min

      protected double getAdditionalStat5Min(RouterContext ctx, String statName)
      Fetch an additional stat value using the 5-minute average.

      Useful for medium-term decisions that need more signal than a 60s spike but faster reaction than a 1-hour trend. For example, retransmit ratio over 5 minutes filters out transient bursts while still catching sustained loss within a minute or two.

      Parameters:
      ctx - the router context
      statName - the stat to query
      Returns:
      the 5-minute rolling average, or NaN if not available
    • getAdditionalEventCountHourly

      protected double getAdditionalEventCountHourly(RouterContext ctx, String statName)
      Fetch the event count for an additional stat using the 1-hour period.
      Parameters:
      ctx - the router context
      statName - the stat to query
      Returns:
      the event count in the last hour, or NaN if not available
    • getStreamingLossRate

      protected double getStreamingLossRate(RouterContext ctx)
      Recent streaming retransmission rate for this tuning cycle.

      One place to compute the rate so every streaming param asks the same question with the same units, instead of each one re-inventing a threshold against sendDuplicateSize (a mean message size in bytes, not a rate — see STREAM_LOSSY_RATE).

      Parameters:
      ctx - the router context
      Returns:
      retransmission rate in [0.0, 1.0], or NaN when there is no signal
      See Also:
    • getBuildSuccessRate

      protected double getBuildSuccessRate(RouterContext ctx)
      Compute actual tunnel build success rate from event counts.

      The build success/failure/timeout stats are event-count markers (addRateData(name, 100, 0)), so getAdditionalStat(RouterContext, String)

      BuildExecutor emits these stats as 0-100 integer percentages with addRateData(name, rate, 0). The eventDuration=0 parameter is not an event count delta — event count always increments by 1 per call. getAdditionalStat(RouterContext, String) returns getAverageValue() = average of emitted rates, which is the correct success percentage. Do NOT use getAdditionalEventCount(RouterContext, String) here — it returns the call count (always 1.0 when all three stats are emitted together), not the rate value.

      Parameters:
      ctx - the router context
      Returns:
      success rate as 0.0–1.0, or NaN if no build events
    • reclaimIfIdle

      protected static int reclaimIfIdle(double utilization, int current, int min, double idleThreshold)
      Reclaim parked threads from a thread pool that is massively under-utilized. Returns the new (shrunk) thread count when the pool utilization is below idleThreshold and more than min threads are allocated, otherwise -1 (no change).

      Utilization is the ratio of threads actively doing work to the total pool size. When this sits near zero for an extended window the extra threads are just parked — there is no point keeping them around, so we shed one (or two, when extremely idle) to track demand.

      Parameters:
      utilization - current pool utilization (0.0–1.0), or NaN
      current - current thread count
      min - minimum thread count (floor)
      idleThreshold - utilization below which threads are reclaimed
      Returns:
      shrunk count, or -1 if no change
    • getCoDelDropEventCount

      protected double getCoDelDropEventCount(RouterContext ctx, String prefix)
      Fetch the total CoDel drop event count across all priority levels.

      CoDelPriorityBlockingQueue emits per-priority stats with names like codel.UDP-Sender.drop.0, codel.UDP-Sender.drop.100, etc. This method sums the event counts across all priorities.

      Parameters:
      ctx - the router context
      prefix - the stat prefix (e.g. "codel.UDP-Sender.drop")
      Returns:
      the total drop event count, or NaN if no priorities have events
    • getObservedRTT

      protected double getObservedRTT(RouterContext ctx, String primaryStat)
      Fetch observed RTT, falling back to udp.sendConfirmTime when the primary stat has no events (lightly loaded router).

      The primary stat is typically a streaming-specific metric (e.g. stream.lifetimeRTT) which only fires when active streaming connections exist. On a lightly loaded router, this may be NaN. The fallback udp.sendConfirmTime is always available when any UDP traffic is present.

      Parameters:
      ctx - the router context
      primaryStat - the streaming-specific RTT stat name
      Returns:
      the observed RTT in ms, or NaN if neither stat has events
    • getReaderUtilization

      protected double getReaderUtilization(RouterContext ctx)
      NTCP reader pool utilization (0.0-1.0).
      Parameters:
      ctx - router context supplying the NTCP transport to read
      Returns:
      the reader utilization
    • getWriterUtilization

      protected double getWriterUtilization(RouterContext ctx)
      NTCP writer pool utilization (0.0-1.0).
      Parameters:
      ctx - router context supplying the NTCP transport to read
      Returns:
      the writer utilization
    • getSendFinisherUtilization

      protected double getSendFinisherUtilization(RouterContext ctx)
      NTCP send finisher pool utilization (0.0-1.0).
      Parameters:
      ctx - router context supplying the NTCP transport to read
      Returns:
      the send finisher utilization
    • getPacketHandlerUtilization

      protected double getPacketHandlerUtilization(RouterContext ctx)
      UDP packet handler pool utilization (0.0-1.0).
      Parameters:
      ctx - router context supplying the UDP transport to read
      Returns:
      the packet handler utilization
    • getMessageReceiverUtilization

      protected double getMessageReceiverUtilization(RouterContext ctx)
      UDP message receiver pool utilization (0.0-1.0).
      Parameters:
      ctx - router context supplying the UDP transport to read
      Returns:
      the message receiver utilization
    • getPumperUtilization

      protected double getPumperUtilization(RouterContext ctx)
      Tunnel pumper pool utilization (0.0-1.0).
      Parameters:
      ctx - router context, unused here; the pumper pool is read statically
      Returns:
      the pumper utilization
    • getCurrentValue

      public int getCurrentValue()
      The value in effect right now.
      Specified by:
      getCurrentValue in interface Tuner.TunableParam
      Returns:
      the runtime value
    • recordHistory

      protected void recordHistory(double observed)
      Record history.
      Parameters:
      observed - the stat reading this value was judged against
    • update

      public void update()
      Main tuning loop for this param. Called each tune cycle: every 5s for transport thread pool params, every 15s for all others.

      Sequence:

      1. Read observed stat via getObservedStat(RouterContext)
      2. Record value/stat history for sparklines
      3. Skip if auto-tuning disabled or stat unavailable
      4. Auto-revert to default if system health < 0.3
      5. Compute target via computeTarget(double)
      6. Apply health-based dampening (reduces step when degraded)
      7. Clamp to [min, max]
      8. Accelerate rollback when param diverges from default
      9. Call applyValue(int) and persistValue(RouterContext, int)
      Specified by:
      update in interface Tuner.TunableParam
    • autoRevertToDefault

      private boolean autoRevertToDefault()
      Auto-revert to the factory default when system health is severely degraded.

      Uses _factoryDefault (the code-level default captured at construction time) rather than _defaultValue which may have been overwritten by stale persisted values from refreshDefault(RouterContext). The reverted value is persisted to autotune.config so that refreshDefault(RouterContext) will not undo it on subsequent cycles.

      Returns:
      true if system health is degraded and revert was attempted
    • dampenTarget

      private int dampenTarget(int target)
      Dampen the computed target: reduce step size when system is degraded.
      Parameters:
      target - the target proposed by the param's feedback logic
      Returns:
      the target moved toward current by the fraction the health score allows, and at least one step toward target whenever the two differ
    • clampTarget

      private int clampTarget(int target)
      Hard clamp the target to [min, max] before comparison.
      Parameters:
      target - the proposed target, possibly outside the param's range
      Returns:
      the target limited to [_min, _max]
    • decisionReason

      protected String decisionReason()
      Why the current target was chosen, for the change line. Optional.

      Returned as a short clause appended after an arrow, so the line reads as event then cause. It is asked only on a cycle that actually moves the value, which is what keeps a diagnostic like this from becoming a per-cycle dump while still tracing every decision that had an effect.

      Returns:
      the reason, or null when the param has nothing to report
    • applyTarget

      private void applyTarget(int target)
      Apply the target value, accelerating rollback when diverged from default.
      Parameters:
      target - the value to move the param to, already clamped to its range
    • clamp

      protected static int clamp(int current, int target, int step)
      Move from current toward target, but at most one step per cycle. Used by computeTarget() implementations to prevent large jumps.
      Parameters:
      current - the current runtime value
      target - the desired target value
      step - the maximum change per cycle
      Returns:
      current moved by at most step toward target; the value is computed and returned, not applied