Players' packets are handled in region list order, not arrival order

Aperta
#531 1 commento 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
5/5
Tempo stimato
Più di una settimana
Idoneità per principianti
25/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
java

Direzione di ricerca

Start with Folia's packet scheduling paths: PacketUtils.ensureRunningOnSameThread and the current CraftPlayer#schedulePacket / PacketProcessor#executeSinglePacket paths cited in the issue. Compare how tickServer drains per-player queues with the proposed sequence-based merge, and inspect the related packet-delay issue #196. Done means packets handled in the same region tick follow their arrival order; the issue notes that the reproduction has not yet been run.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

status: needs triage type: bug
Expected behavior

When two players in the same region send packets, the server handles them in the order they arrived, the way Paper does. On Paper, every connection's game packets go into one server-wide FIFO queue (BlockableEventLoop.pendingRunnables on 1.21.4, the server PacketProcessor on current versions). On 1.21.4 that queue is drained between ticks and again at the end of the tick. If V's packet arrives before B's, V's packet is applied first.

Observed/Actual behavior

On Folia, each player's game packets wait in that player's own queue, and the region handles them one player at a time:

  • 1.21.4: PacketUtils.ensureRunningOnSameThread schedules each packet on the player's EntityScheduler with a delay of 1. tickServer runs those schedulers in RegionizedWorldData.getLocalEntitiesCopy() order. That list is a ReferenceList: new entities are appended, a removed entity's slot is filled by the last entry, and a merged region's entities are appended. Its order depends on when each entity entered the region and on which entities were removed since. Packet arrival time plays no part.
  • Current ver/26.3.x (from reading the source, not tested): packets go to a per-player PacketProcessor. At tick start, tickServer empties each player's queue completely, one player after another, in getLocalPlayers() (join) order. The default EDF scheduler runs no tasks between ticks, so this tick-start pass handles everything that arrived during the previous tick. With WORK_STEALING, drainOnePacket also runs between ticks, taking one packet per player per pass in the same order.

So when packets from several players land in the same batch, the player who is earlier in the list always goes first, even if their packet arrived last. In PvP this decides who survives. Packet log from a large public Folia 1.21.4 server (times are when V's client received each packet; V's round-trip time is 7-30 ms):

  • 18:44:13.410 Attacker A's hit pops V's offhand totem (DamageEvent + EntityEvent 35). Per the client's code, it sends an inventory SWAP click (a totem into the offhand) on the next frame. That outgoing click is not captured in this log.
  • 18:44:13.451 That tick's SetHealth (2.0, absorption 8). V is alive.
  • 18:44:13.463 Attacker B's hit kills V (PlayerCombatKill). There is no DamageEvent and no death sound, because it was a top-up hit inside A's invulnerability window (amount - lastHurt, flag1 == false in LivingEntity.hurtServer). After that, V's swap is dropped, because handleContainerClick returns early once isImmobile() is true.

Calibration from a pop V survived earlier in the same fight: the reply to the swap (SetSlot) came 58 ms after the pop, which is 5 ms after that tick's SetHealth, so it was handled at the start of the next tick. So in the fatal case, the swap reached the server about 10-30 ms after the pop and was already queued when the next tick began, yet B's attack ran ahead of it in that tick. All three attackers have lower entity ids than V (they were created earlier), which fits them being ahead of V in the list. V's side cannot show whether B's packet arrived before or after V's swap; the repro below shows that on Folia the outcome is the same either way.

Steps/models to reproduce

Not yet run as written; the expected result follows from the code linked below.

  1. Folia 1.21.4, flat world, /gamerule doMobSpawning false (so the region's entity list stays put). In the ServerGamePacketListenerImpl branch of PacketUtils.ensureRunningOnSameThread, add:
    final long seq = DEBUG_SEQ.incrementAndGet(); // static final AtomicLong, taken on the netty thread
    final String who = gamePacketListener.player.getScoreboardName();
    // first line of the scheduled lambda, before run.run():
    LOGGER.info("handled seq={} player={} packet={}", seq, who, packet.getClass().getSimpleName());
    
  2. Join with vanilla client Alice, then vanilla client Bob. Stand next to each other and both keep walking, so each client sends movement packets every tick.
  3. Expected: within each region tick, all of Alice's lines print before any of Bob's, so seq jumps backwards whenever Bob's packet arrived first. On Paper, the equivalent log prints seq in increasing order.
  4. Have Alice reconnect. She is re-added at the end of the list, and from then on Bob's packets run first.

Combat version: B joins before V. B's first hit pops V's offhand totem. V presses F over a totem in the open inventory (a SWAP click into the offhand). Within 10 ticks of the first hit, B lands a larger follow-up hit (for example a crit, or a mace smash). When the swap and the follow-up hit reach the server during the same tick, B's hit is applied first and V dies. With the join order reversed, the swap is applied first and the second totem pops. On 26.3.x the instrumentation would go in CraftPlayer#schedulePacket and PacketProcessor#executeSinglePacket.

Plugin and Datapack List

Paper plugins (3): DisplayEntities (1.5.0+17), PlugManX (3.2.1), Worlds (3.12.3-mc1.21.4)
Bukkit plugins (33): AnarchyExploitFixes (2.7.12), AntiHealthIndicator (2.5.1), AntiPopup (13.3), ChestCommands (4.0.5-folia.1), CommandWhitelist (2.13.1), CoreProtect (24.1), DeathMessages (1.0.7-fork.2), Essentials (2.22.1-dev+50-eb66dc1-Folia), EssentialsSpawn (2.22.1-dev+50-eb66dc1-Folia), FreeFrame (1.0.0), GrimAC (2.3.75-1299a2a), GrimTpsFix (1.0.0), KitCreator (1.0.0), LuckPerms (5.5.71), MiniMOTD (2.2.5), NBTAPI (2.16.1), PassivePhantoms (1.3.0-Dev2a), PistonChat (2.2.0), PlaceholderAPI (2.12.3), ProjectileBlocker (2.3.0), RecipeBook (1.1.0), Respawn (1.0.0), ServerTooltip (1.0.0), SlowRegen (1.0.0), SpawnDistance (1.0.0), TAB (6.2.1), ViaBackwards (5.12.2), ViaVersion (5.12.2), ViewDistanceTweaks (1.5.7-folia1), VoidDamage (1.0.0), WorldEdit (7.4.6+7648-00664b0), WorldGuard (7.0.17), packetevents (2.14.0)

Datapacks: /datapack is not registered on Folia 1.21.4 (commented out in Folia's source as "region threading - TODO"), so it returns "Unknown or incomplete command". Every world's level.dat has Enabled: vanilla, file/bukkit, paper (Disabled: minecart_improvements, redstone_experiments, trade_rebalance).

Folia version

Checking version, please wait...
This server is running Folia version 1.21.4-6-ver/1.21.4@b785bcc (2025-06-13T21:52:33Z) (Implementing API version 1.21.4-R0.1-SNAPSHOT)
Error obtaining version information
Previous version: 1.21.4-DEV-175e5e7 (MC: 1.21.4)

Other
Source references
Suggested fix

When a game packet is queued, stamp it on the netty thread with a global monotonic sequence number (one AtomicLong.incrementAndGet()). In the tick-start pass, merge the region's per-player queues by that number: repeatedly take the player whose oldest pending packet has the lowest number (for example, from a small heap of players that have packets), instead of emptying one player at a time. drainOnePacket could choose the same way. All other entity-scheduler work stays as it is. Trade-offs:

  • A handler can move its player out of the region during the merge. That player's remaining packets would then wait for the new region, as they do today (the existing isTickThreadFor check covers this).
  • Cost: O(log p) per packet, where p is the number of players with pending packets, plus one shared atomic counter.
  • This only fixes ordering within a region tick. The wait of up to one tick (#196) is a separate issue.

Related: #196 (packets wait for the next tick). I found no existing issue about cross-player ordering.

Lingua principale
Shell
Stelle
4.7k
Fork
651
Merge medio
10g 3h
PR unite (30g)
3

Preparare l'ambiente

Questo progetto non fornisce container di sviluppo, Dockerfile né guida per i contributori, quindi l'ambiente è a tuo carico: parti dal suo README e consulta la nostra guida al primo contributo per i passaggi generali.

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di PaperMC/Folia

Tutte le issue di PaperMC/Folia

Issue simili

Altre issue su Shell/Bash

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.