Add direct element runner for DirectWindowedElementFn in FnApiDoFnRunner
diff --git a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/FnApiDoFnRunner.java b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/FnApiDoFnRunner.java
index edc6477..a7f8f63 100644
--- a/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/FnApiDoFnRunner.java
+++ b/sdks/java/harness/src/main/java/org/apache/beam/fn/harness/FnApiDoFnRunner.java
@@ -23,6 +23,7 @@
 
 import com.google.auto.service.AutoService;
 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import io.opentelemetry.context.Scope;
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -74,6 +75,7 @@
 import org.apache.beam.sdk.state.StateSpec;
 import org.apache.beam.sdk.state.TimeDomain;
 import org.apache.beam.sdk.state.TimerMap;
+import org.apache.beam.sdk.transforms.DirectWindowedElementFn;
 import org.apache.beam.sdk.transforms.DoFn;
 import org.apache.beam.sdk.transforms.DoFn.BundleFinalizer;
 import org.apache.beam.sdk.transforms.DoFn.MultiOutputReceiver;
@@ -166,6 +168,9 @@
 
     @Override
     public final void addRunnerForPTransform(Context context) throws IOException {
+      if (tryAddDirectWindowedElementRunner(context)) {
+        return;
+      }
 
       FnApiStateAccessor<Object> stateAccessor =
           FnApiStateAccessor.Factory.factoryForPTransformContext(context).create();
@@ -205,6 +210,102 @@
         }
       }
     }
+
+    @SuppressWarnings({"unchecked", "nullness"})
+    private boolean tryAddDirectWindowedElementRunner(Context context) throws IOException {
+      PTransform pTransform = context.getPTransform();
+      if (!PTransformTranslation.PAR_DO_TRANSFORM_URN.equals(pTransform.getSpec().getUrn())
+          || pTransform.getOutputsCount() != 1) {
+        return false;
+      }
+      ParDoPayload payload = ParDoPayload.parseFrom(pTransform.getSpec().getPayload());
+      if (!payload.getSideInputsMap().isEmpty()
+          || !payload.getStateSpecsMap().isEmpty()
+          || !payload.getTimerFamilySpecsMap().isEmpty()
+          || payload.getRequestsFinalization()) {
+        return false;
+      }
+      DoFn<?, ?> fn = ParDoTranslation.getDoFn(payload);
+      if (!(fn instanceof DirectWindowedElementFn)) {
+        return false;
+      }
+      DoFnSignature sig = DoFnSignatures.signatureForDoFn(fn);
+      if (sig.processElement().observesWindow()
+          || sig.processElement().isSplittable()
+          || sig.setup() != null
+          || sig.startBundle() != null
+          || sig.finishBundle() != null
+          || sig.teardown() != null
+          || sig.onWindowExpiration() != null) {
+        return false;
+      }
+      RehydratedComponents rehydrated =
+          RehydratedComponents.forComponents(context.getComponents())
+              .withPipeline(Pipeline.create());
+      TupleTag<?> mainOutputTag = ParDoTranslation.getMainOutputTag(payload);
+      String outPCollectionId = pTransform.getOutputsMap().get(mainOutputTag.getId());
+      if (outPCollectionId == null) {
+        return false;
+      }
+      Coder<?> outCoder =
+          rehydrated.getCoder(
+              context.getComponents().getPcollectionsOrThrow(outPCollectionId).getCoderId());
+      if (outCoder instanceof WindowedValueCoder) {
+        outCoder = ((WindowedValueCoder<?>) outCoder).getValueCoder();
+      }
+      if (outCoder instanceof SchemaCoder) {
+        return false;
+      }
+
+      String inPCollectionId = Iterables.getOnlyElement(pTransform.getInputsMap().values());
+      final DirectWindowedElementFn<InputT, OutputT> directFn =
+          (DirectWindowedElementFn<InputT, OutputT>) fn;
+      final FnDataReceiver<WindowedValue<OutputT>> downstream =
+          (FnDataReceiver<WindowedValue<OutputT>>)
+              (FnDataReceiver) context.getPCollectionConsumer(outPCollectionId);
+      context.addPCollectionConsumer(
+          inPCollectionId,
+          (WindowedValue<InputT> elem) -> {
+            io.opentelemetry.context.Context otel = elem.getOpenTelemetryContext();
+            if (otel != null && otel != io.opentelemetry.context.Context.current()) {
+              try (Scope ignored = otel.makeCurrent()) {
+                invokeDirectElementFn(directFn, elem, downstream);
+              }
+            } else {
+              invokeDirectElementFn(directFn, elem, downstream);
+            }
+          });
+      return true;
+    }
+
+    private static boolean hasChangedOtel(WindowedValue<?> elem) {
+      io.opentelemetry.context.Context curOtel = io.opentelemetry.context.Context.current();
+      io.opentelemetry.context.Context elemOtel = elem.getOpenTelemetryContext();
+      return curOtel != elemOtel
+          && !(curOtel == io.opentelemetry.context.Context.root() && elemOtel == null);
+    }
+
+    private void invokeDirectElementFn(
+        DirectWindowedElementFn<InputT, OutputT> directFn,
+        WindowedValue<InputT> elem,
+        FnDataReceiver<WindowedValue<OutputT>> downstream)
+        throws Exception {
+      WindowedValue<OutputT> out;
+      try {
+        out = directFn.processElementDirect(elem);
+      } catch (OutOfMemoryError oom) {
+        throw oom;
+      } catch (Throwable t) {
+        throw UserCodeException.wrap(t);
+      }
+      if (out == null) {
+        return;
+      }
+      if (hasChangedOtel(elem)) {
+        out = WindowedValues.builder(out).build();
+      }
+      downstream.accept(out);
+    }
   }
 
   //////////////////////////////////////////////////////////////////////////////////////////////////
diff --git a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/FnApiDoFnRunnerTest.java b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/FnApiDoFnRunnerTest.java
index 4166b2a..b3bc673 100644
--- a/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/FnApiDoFnRunnerTest.java
+++ b/sdks/java/harness/src/test/java/org/apache/beam/fn/harness/FnApiDoFnRunnerTest.java
@@ -38,6 +38,8 @@
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 
+import io.opentelemetry.context.Context;
+import io.opentelemetry.context.ContextKey;
 import java.io.Closeable;
 import java.io.IOException;
 import java.io.Serializable;
@@ -102,6 +104,10 @@
 import org.apache.beam.sdk.transforms.Combine.CombineFn;
 import org.apache.beam.sdk.transforms.Create;
 import org.apache.beam.sdk.transforms.DoFn;
+import org.apache.beam.sdk.transforms.Filter;
+import org.apache.beam.sdk.transforms.MapElements;
+import org.apache.beam.sdk.transforms.MapKeys;
+import org.apache.beam.sdk.transforms.MapValues;
 import org.apache.beam.sdk.transforms.ParDo;
 import org.apache.beam.sdk.transforms.View;
 import org.apache.beam.sdk.transforms.splittabledofn.OffsetRangeTracker;
@@ -132,6 +138,8 @@
 import org.apache.beam.sdk.values.Row;
 import org.apache.beam.sdk.values.TupleTag;
 import org.apache.beam.sdk.values.TupleTagList;
+import org.apache.beam.sdk.values.TypeDescriptors;
+import org.apache.beam.sdk.values.ValueKind;
 import org.apache.beam.sdk.values.WindowedValue;
 import org.apache.beam.sdk.values.WindowedValues;
 import org.apache.beam.vendor.grpc.v1p69p0.com.google.protobuf.ByteString;
@@ -2935,6 +2943,237 @@
       }
     }
 
+    private static final ContextKey<String> INLINE_OTEL_KEY = ContextKey.named("inline-otel-test");
+
+    private static RunnerApi.PTransform findParDoProducing(
+        RunnerApi.Pipeline pProto, String outputPCollectionId) {
+      for (RunnerApi.PTransform t : pProto.getComponents().getTransformsMap().values()) {
+        if (PTransformTranslation.PAR_DO_TRANSFORM_URN.equals(t.getSpec().getUrn())
+            && t.getOutputsMap().containsValue(outputPCollectionId)) {
+          return t;
+        }
+      }
+      throw new AssertionError("No ParDo transform producing " + outputPCollectionId);
+    }
+
+    @Test
+    public void testInlineableMapAndFilterFastPath() throws Exception {
+      // Inline MAP: preserves metadata, activates element OTel context, wraps exceptions.
+      Pipeline mapPipeline = Pipeline.create();
+      PCollection<String> mapIn = mapPipeline.apply(Create.of("a"));
+      PCollection<String> mapOut =
+          mapIn.apply(
+              TEST_TRANSFORM_ID,
+              MapElements.into(TypeDescriptors.strings())
+                  .via(
+                      s -> {
+                        if ("boom".equals(s)) {
+                          throw new IllegalStateException("map failure");
+                        }
+                        return s + ":" + Context.current().get(INLINE_OTEL_KEY);
+                      }));
+
+      SdkComponents mapComponents = SdkComponents.create(mapPipeline.getOptions());
+      RunnerApi.Pipeline mapProto = PipelineTranslation.toProto(mapPipeline, mapComponents);
+      String mapInId = mapComponents.registerPCollection(mapIn);
+      String mapOutId = mapComponents.registerPCollection(mapOut);
+      PTransformRunnerFactoryTestContext mapCtx =
+          PTransformRunnerFactoryTestContext.builder(
+                  TEST_TRANSFORM_ID, findParDoProducing(mapProto, mapOutId))
+              .processBundleInstructionId("57")
+              .components(mapProto.getComponents())
+              .build();
+      List<WindowedValue<String>> mapResults = new ArrayList<>();
+      mapCtx.addPCollectionConsumer(
+          mapOutId, (FnDataReceiver) new OutputFnDataReceiver(mapResults));
+
+      new FnApiDoFnRunner.Factory<>().addRunnerForPTransform(mapCtx);
+      // Direct inline path bypasses FnApiDoFnRunner start/finish bundle registration.
+      assertThat(mapCtx.getStartBundleFunctions(), empty());
+      assertThat(mapCtx.getFinishBundleFunctions(), empty());
+
+      Context outer = Context.current();
+      Context elemOtel = Context.root().with(INLINE_OTEL_KEY, "trace-123");
+      WindowedValue<String> inputElem =
+          WindowedValues.of(
+              "hi",
+              new Instant(42L),
+              GlobalWindow.INSTANCE,
+              PaneInfo.NO_FIRING,
+              "rec-1",
+              99L,
+              CausedByDrain.CAUSED_BY_DRAIN,
+              elemOtel,
+              ValueKind.INSERT);
+      FnDataReceiver<WindowedValue<?>> mapConsumer = mapCtx.getPCollectionConsumer(mapInId);
+      mapConsumer.accept(inputElem);
+      assertEquals(outer, Context.current());
+      assertThat(mapResults, hasSize(1));
+      WindowedValue<String> mapped = mapResults.get(0);
+      assertEquals("hi:trace-123", mapped.getValue());
+      assertEquals(new Instant(42L), mapped.getTimestamp());
+      assertEquals("rec-1", mapped.getRecordId());
+      assertEquals(Long.valueOf(99L), mapped.getRecordOffset());
+      assertEquals(CausedByDrain.CAUSED_BY_DRAIN, mapped.causedByDrain());
+      assertEquals(elemOtel, mapped.getOpenTelemetryContext());
+
+      UserCodeException mapEx =
+          assertThrows(
+              UserCodeException.class, () -> mapConsumer.accept(valueInGlobalWindow("boom")));
+      assertThat(mapEx.getCause(), instanceOf(IllegalStateException.class));
+
+      // Inline FILTER: keeps matching elements with metadata, drops non-matching, wraps throws.
+      Pipeline filterPipeline = Pipeline.create();
+      PCollection<String> filterIn = filterPipeline.apply(Create.of("a"));
+      PCollection<String> filterOut =
+          filterIn.apply(
+              TEST_TRANSFORM_ID,
+              Filter.by(
+                  s -> {
+                    if ("boom".equals(s)) {
+                      throw new IllegalArgumentException("filter failure");
+                    }
+                    return "keep".equals(s)
+                        && "trace-123".equals(Context.current().get(INLINE_OTEL_KEY));
+                  }));
+
+      SdkComponents filterComponents = SdkComponents.create(filterPipeline.getOptions());
+      RunnerApi.Pipeline filterProto =
+          PipelineTranslation.toProto(filterPipeline, filterComponents);
+      String filterInId = filterComponents.registerPCollection(filterIn);
+      String filterOutId = filterComponents.registerPCollection(filterOut);
+      PTransformRunnerFactoryTestContext filterCtx =
+          PTransformRunnerFactoryTestContext.builder(
+                  TEST_TRANSFORM_ID, findParDoProducing(filterProto, filterOutId))
+              .processBundleInstructionId("58")
+              .components(filterProto.getComponents())
+              .build();
+      List<WindowedValue<String>> filterResults = new ArrayList<>();
+      filterCtx.addPCollectionConsumer(
+          filterOutId, (FnDataReceiver) new OutputFnDataReceiver(filterResults));
+
+      new FnApiDoFnRunner.Factory<>().addRunnerForPTransform(filterCtx);
+      assertThat(filterCtx.getStartBundleFunctions(), empty());
+      assertThat(filterCtx.getFinishBundleFunctions(), empty());
+
+      FnDataReceiver<WindowedValue<?>> filterConsumer =
+          filterCtx.getPCollectionConsumer(filterInId);
+      filterConsumer.accept(inputElem.withValue("drop"));
+      filterConsumer.accept(inputElem.withValue("keep"));
+      assertEquals(outer, Context.current());
+      assertThat(filterResults, hasSize(1));
+      assertEquals("keep", filterResults.get(0).getValue());
+      assertEquals("rec-1", filterResults.get(0).getRecordId());
+      assertEquals(elemOtel, filterResults.get(0).getOpenTelemetryContext());
+
+      UserCodeException filterEx =
+          assertThrows(
+              UserCodeException.class, () -> filterConsumer.accept(valueInGlobalWindow("boom")));
+      assertThat(filterEx.getCause(), instanceOf(IllegalArgumentException.class));
+
+      // MapKeys and MapValues bypass Contextful and use the direct element fast path too.
+      Pipeline kvPipeline = Pipeline.create();
+      PCollection<KV<String, String>> kvIn = kvPipeline.apply(Create.of(KV.of("k", "v")));
+      PCollection<KV<String, String>> mappedKeys =
+          kvIn.apply("MapKeys", MapKeys.into(TypeDescriptors.strings()).via((String k) -> k + "!"))
+              .setCoder(KvCoder.of(StringUtf8Coder.of(), StringUtf8Coder.of()));
+      PCollection<KV<String, String>> mappedVals =
+          mappedKeys
+              .apply(
+                  "MapValues", MapValues.into(TypeDescriptors.strings()).via((String v) -> v + "?"))
+              .setCoder(KvCoder.of(StringUtf8Coder.of(), StringUtf8Coder.of()));
+      SdkComponents kvComponents = SdkComponents.create(kvPipeline.getOptions());
+      RunnerApi.Pipeline kvProto = PipelineTranslation.toProto(kvPipeline, kvComponents);
+      String kvInId = kvComponents.registerPCollection(kvIn);
+      String mappedKeysId = kvComponents.registerPCollection(mappedKeys);
+      String mappedValsId = kvComponents.registerPCollection(mappedVals);
+
+      PTransformRunnerFactoryTestContext mkCtx =
+          PTransformRunnerFactoryTestContext.builder(
+                  "MapKeys", findParDoProducing(kvProto, mappedKeysId))
+              .processBundleInstructionId("61")
+              .components(kvProto.getComponents())
+              .build();
+      List<WindowedValue<KV<String, String>>> mkResults = new ArrayList<>();
+      mkCtx.addPCollectionConsumer(
+          mappedKeysId,
+          (FnDataReceiver) (FnDataReceiver<WindowedValue<KV<String, String>>>) mkResults::add);
+      new FnApiDoFnRunner.Factory<>().addRunnerForPTransform(mkCtx);
+      assertThat(mkCtx.getStartBundleFunctions(), empty());
+      assertThat(mkCtx.getFinishBundleFunctions(), empty());
+      mkCtx.getPCollectionConsumer(kvInId).accept(valueInGlobalWindow(KV.of("a", "b")));
+      assertEquals(KV.of("a!", "b"), Iterables.getOnlyElement(mkResults).getValue());
+
+      PTransformRunnerFactoryTestContext mvCtx =
+          PTransformRunnerFactoryTestContext.builder(
+                  "MapValues", findParDoProducing(kvProto, mappedValsId))
+              .processBundleInstructionId("62")
+              .components(kvProto.getComponents())
+              .build();
+      List<WindowedValue<KV<String, String>>> mvResults = new ArrayList<>();
+      mvCtx.addPCollectionConsumer(
+          mappedValsId,
+          (FnDataReceiver) (FnDataReceiver<WindowedValue<KV<String, String>>>) mvResults::add);
+      new FnApiDoFnRunner.Factory<>().addRunnerForPTransform(mvCtx);
+      assertThat(mvCtx.getStartBundleFunctions(), empty());
+      assertThat(mvCtx.getFinishBundleFunctions(), empty());
+      mvCtx.getPCollectionConsumer(mappedKeysId).accept(valueInGlobalWindow(KV.of("a!", "b")));
+      assertEquals(KV.of("a!", "b?"), Iterables.getOnlyElement(mvResults).getValue());
+    }
+
+    @Test
+    public void testInlineableFunctionSkipsSchemaCoderAndSideOnlyOutput() throws Exception {
+      // SchemaCoder output must fall back to full FnApiDoFnRunner.
+      Schema schema = Schema.builder().addStringField("f").build();
+      Pipeline schemaPipeline = Pipeline.create();
+      PCollection<String> schemaIn = schemaPipeline.apply(Create.of("x"));
+      PCollection<Row> schemaOut =
+          schemaIn
+              .apply(
+                  TEST_TRANSFORM_ID,
+                  MapElements.into(TypeDescriptors.rows())
+                      .via(s -> Row.withSchema(schema).addValue(s).build()))
+              .setRowSchema(schema);
+
+      SdkComponents schemaComponents = SdkComponents.create(schemaPipeline.getOptions());
+      RunnerApi.Pipeline schemaProto =
+          PipelineTranslation.toProto(schemaPipeline, schemaComponents);
+      String schemaOutId = schemaComponents.registerPCollection(schemaOut);
+      PTransformRunnerFactoryTestContext schemaCtx =
+          PTransformRunnerFactoryTestContext.builder(
+                  TEST_TRANSFORM_ID, findParDoProducing(schemaProto, schemaOutId))
+              .processBundleInstructionId("59")
+              .components(schemaProto.getComponents())
+              .build();
+      schemaCtx.addPCollectionConsumer(
+          schemaOutId, (FnDataReceiver) new OutputFnDataReceiver(new ArrayList<>()));
+      new FnApiDoFnRunner.Factory<>().addRunnerForPTransform(schemaCtx);
+      assertThat(schemaCtx.getFinishBundleFunctions(), hasSize(1));
+
+      // Single output wired only to a non-main tag must fall back without NPE.
+      Pipeline sidePipeline = Pipeline.create();
+      PCollection<String> sideIn = sidePipeline.apply(Create.of("x"));
+      PCollection<String> sideOut =
+          sideIn.apply(TEST_TRANSFORM_ID, MapElements.into(TypeDescriptors.strings()).via(s -> s));
+      SdkComponents sideComponents = SdkComponents.create(sidePipeline.getOptions());
+      RunnerApi.Pipeline sideProto = PipelineTranslation.toProto(sidePipeline, sideComponents);
+      String sideOutId = sideComponents.registerPCollection(sideOut);
+      RunnerApi.PTransform sideOnlyTransform =
+          findParDoProducing(sideProto, sideOutId).toBuilder()
+              .clearOutputs()
+              .putOutputs("side", sideOutId)
+              .build();
+      PTransformRunnerFactoryTestContext sideCtx =
+          PTransformRunnerFactoryTestContext.builder(TEST_TRANSFORM_ID, sideOnlyTransform)
+              .processBundleInstructionId("60")
+              .components(sideProto.getComponents())
+              .build();
+      sideCtx.addPCollectionConsumer(
+          sideOutId, (FnDataReceiver) new OutputFnDataReceiver(new ArrayList<>()));
+      new FnApiDoFnRunner.Factory<>().addRunnerForPTransform(sideCtx);
+      assertThat(sideCtx.getFinishBundleFunctions(), hasSize(1));
+    }
+
     @Test
     public void testDoFnSkewNotAllowed() throws Exception {
       Pipeline p = Pipeline.create();