Hacktoberfest 2026: los issues que los mantenedores marcaron para octubre, abiertos y aptos para principiantes. Explorar issues de Hacktoberfest

[Bug]: TagBatch reuses a cached PlcReadRequest bound to a closed connection, so fetches fail after the first and never recover after a PLC restart

Abierto
#2,832 0 comentarios 0 reacciones 1 asignado Ver en GitHub

Los mantenedores suelen responder en 1 día

@chrisdutz ya está trabajando en esto.

Desde el 26/10/2026.

Evaluación

Dificultad
3/5
Tiempo estimado
1-2 días
Aptitud para principiantes
72/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
java

Línea de trabajo

Read plc4j/tools/event-pump/src/main/java/org/apache/plc4x/java/tools/eventpump/TagBatch.java, focusing on fetchTags(), request caching, connection closing, and invalidateCache(). Reproduce with the issue's TagBatch example using DefaultPlcDriverManager, then repeat with PlcConnectionCache and restart the Modbus simulator. Done means later fetches use the current connection and continue after a PLC restart; add or update event-pump tests covering repeated fetches and recovery.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

What happened?

TagBatch in plc4j-tools-event-pump builds its PlcReadRequest once and caches it (keyed only on the tag snapshot), but it obtains a connection from the configured PlcConnectionFactory on every fetch and closes that connection after the fetch. A PlcReadRequest is bound to the connection whose builder created it (DefaultPlcReadRequest keeps the PlcReader; execute() calls reader.read(this)), so the cached request keeps targeting the connection of the first fetch. Once that connection is closed, every later fetch fails without ever using the connection that was just opened for it.

Observed against a Modbus TCP simulator (oitc/modbus-server, Docker) with plc4j-tools-event-pump 1.0.0, plc4j-driver-modbus 1.0.0, TimerTrigger(100 ms), three tags (coil:1, holding-register:1:INT, holding-register:2:INT):

  1. DefaultPlcDriverManager as connection factory (a new connection per fetch): fetch 1 succeeds, fetch 2 and every later attempt fail immediately with PlcRuntimeException: Failed to send request, root cause TransportException: Transport is closed at TcpTransportInstance.ensureOpen(TcpTransportInstance.java:319). Each attempt still logs "Modbus TCP connection established" for a connection that is never used. In 5 s: 1 fetch, 3 errors, back-off 1 s, 2 s, 4 s.
  2. PlcConnectionCache as connection factory (one physical connection, a lease per fetch): 49 fetches in 5 s while the simulator is up. After docker stop / docker start of the simulator the batch never recovers: 0 fetches in the following 65 s, every attempt fails with Transport is closed, and no "Connection refused" ever appears because the network is never touched. Even after the cache's idle validation detected the dead connection and opened a new one (at about +58 s), the next fetch failed again: the cached request still targets the old connection.

Cause, same on develop as in 1.0.0 (plc4j/tools/event-pump/src/main/java/org/apache/plc4x/java/tools/eventpump/TagBatch.java):

  • fetchTags() calls connectionFactory.getConnection(connectionString) per fetch (line 516) and closes the connection in the completion handler (lines 604 and 621).
  • The read request is cached in cachedReadRequest / cachedTagSnapshot (lines 122-123) and reused whenever the tag snapshot is unchanged (lines 529-541).
  • invalidateCache() (lines 712-715) is private and is only called by addTag(s) / removeTag(s) / clearTags, never on a fetch error or on a different connection.

Expected: a fetch executes its read request on the connection it obtained for that fetch, so a batch over DefaultPlcDriverManager keeps working and a batch over PlcConnectionCache recovers once the PLC is reachable again (the back-off then does its job instead of retrying a dead request forever).

Possible fixes, in order of simplicity: build the request on the connection of the current fetch (the PlcReadRequest.Builder cost is small compared to a network round trip); or cache the request per connection instance; or at least call invalidateCache() on every fetch error.

Workaround we verified: calling removeTag(name) + addTag(name, address) from TagBatchListener.onError forces a rebuild; with PlcConnectionCache the batch then recovers after a simulator restart (275 fetches in the 30 s after docker start, 3 errors in total). Side effect: the tag order in later responses changes.

Reproduction (JDK 21, plc4j-api, plc4j-tools-event-pump, plc4j-driver-modbus 1.0.0 on the classpath; docker run -d -p 127.0.0.1:5020:5020 oitc/modbus-server:latest):

TagBatch batch = TagBatch.builder()
        .withBatchId("repro")
        .withConnectionFactory(new DefaultPlcDriverManager())
        .withConnectionString("modbus-tcp://127.0.0.1:5020")
        .addTagAddress("c1", "coil:1")
        .withTrigger(new TimerTrigger(100, TimeUnit.MILLISECONDS))
        .withListener(new TagBatchListener() {
            @Override
            public void onTagsFetched(TagBatch b, PlcReadResponse r) {
                System.out.println("fetched " + r.getResponseCode("c1"));
            }

            @Override
            public void onError(TagBatch b, Throwable t) {
                System.out.println("error " + t);
            }
        })
        .build();
batch.start();
Thread.sleep(5000);
batch.close();

Output: one fetched OK, then only error ... Transport is closed lines. Replace the factory with PlcConnectionCache.getBuilder().withConnectionFactory(new DefaultPlcDriverManager()).build(), restart the simulator while the batch runs, and the error lines never stop.

Found while porting Apache Camel's camel-plc4x triggered consumer from plc4j-scraper to the event pump (CAMEL-25617).

Version

v1.0.0 (code unchanged on develop as of 2026-10-23)

Programming Languages
  • plc4c
  • plc4go
  • plc4j
  • plc4net
  • plc4py
Protocols
  • Modbus (used for the reproduction; the cause is protocol-independent)
Lenguaje dominante
Java
Estrellas
1.8k
Forks
514
Merge medio
2 d 2 h
PR fusionados (30 d)
34

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de apache/plc4x

Todos los issues de apache/plc4x

Issues similares

Más issues de Java

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.