This is an automated email from the ASF dual-hosted git repository.

joerghoh pushed a commit to branch master
in repository 
https://gitbox.apache.org/repos/asf/sling-org-apache-sling-event.git


The following commit(s) were added to refs/heads/master by this push:
     new a8b2df1  SLING-13429 add diagnostics for unassigned jobs (#62)
a8b2df1 is described below

commit a8b2df14239d3194bbc5e7be0427275f11669b93
Author: Jörg Hoh <[email protected]>
AuthorDate: Mon Nov 16 14:07:03 2026 +0100

    SLING-13429 add diagnostics for unassigned jobs (#62)
---
 .../sling/event/impl/jobs/JobConsumerManager.java  | 173 ++++++++++++++++++---
 .../sling/event/impl/jobs/JobManagerImpl.java      |  32 +++-
 .../impl/jobs/config/JobManagerConfiguration.java  |  15 ++
 .../impl/jobs/config/TopologyCapabilities.java     |  12 +-
 .../event/impl/jobs/JobConsumerManagerTest.java    | 121 ++++++++++++++
 .../sling/event/impl/jobs/JobManagerImplTest.java  | 170 ++++++++++++++++++--
 .../jobs/config/JobManagerConfigurationTest.java   |  21 +++
 .../org/apache/sling/event/it/JobHandlingIT.java   |   7 +-
 8 files changed, 515 insertions(+), 36 deletions(-)

diff --git 
a/src/main/java/org/apache/sling/event/impl/jobs/JobConsumerManager.java 
b/src/main/java/org/apache/sling/event/impl/jobs/JobConsumerManager.java
index ab7837d..0ee7ae0 100644
--- a/src/main/java/org/apache/sling/event/impl/jobs/JobConsumerManager.java
+++ b/src/main/java/org/apache/sling/event/impl/jobs/JobConsumerManager.java
@@ -110,6 +110,13 @@ public class JobConsumerManager {
 
     private String topics;
 
+    /** Diagnostic state only, guarded by topicToConsumerMap; never used to 
control publication. */
+    private long publicationCycle;
+
+    private boolean publicationPending;
+
+    private int publicationWindowChanges;
+
     private TopicMatcher[] allowListMatchers;
 
     private TopicMatcher[] denyListMatchers;
@@ -185,24 +192,64 @@ public class JobConsumerManager {
 
         final boolean enable = this.allowListMatchers != null && 
this.denyListMatchers != TopicMatcherHelper.MATCH_ALL;
         if (wasEnabled != enable) {
+            final long cycle;
+            final String initialTopics;
             synchronized (this.topicToConsumerMap) {
-                this.calculateTopics(enable);
+                this.topics = this.calculateTopics(enable);
+                if (enable) {
+                    this.publicationCycle++;
+                    this.publicationPending = true;
+                    this.publicationWindowChanges = 0;
+                }
+                cycle = this.publicationCycle;
+                initialTopics = this.topics;
             }
             if (enable) {
+                logger.info(
+                        "Consumer topic provider registration starting; 
cycle={}, publicationEnabled=true, topics={}",
+                        cycle,
+                        initialTopics);
                 logger.debug("Registering property provider with: {}", 
this.topics);
-                this.propagationService = bc.registerService(
-                        PropertyProvider.class,
-                        new PropertyProvider() {
-
-                            @Override
-                            public String getProperty(final String name) {
-                                if 
(TopologyCapabilities.PROPERTY_TOPICS.equals(name)) {
-                                    return topics;
+                boolean completed = false;
+                try {
+                    this.propagationService = bc.registerService(
+                            PropertyProvider.class,
+                            new PropertyProvider() {
+
+                                @Override
+                                public String getProperty(final String name) {
+                                    if 
(TopologyCapabilities.PROPERTY_TOPICS.equals(name)) {
+                                        final String value = topics;
+                                        logger.debug(
+                                                "Discovery reading consumer 
topics; cycle={}, topics={}", cycle, value);
+                                        return value;
+                                    }
+                                    return null;
                                 }
-                                return null;
-                            }
-                        },
-                        this.getRegistrationProperties());
+                            },
+                            this.getRegistrationProperties());
+                    completed = true;
+                } finally {
+                    final String expected;
+                    final String actual;
+                    final int changes;
+                    synchronized (this.topicToConsumerMap) {
+                        this.publicationPending = false;
+                        changes = this.publicationWindowChanges;
+                        expected = this.calculateTopics(true);
+                        actual = this.topics;
+                    }
+                    // Observe only: do not replace the published topics or 
send a corrective modification event.
+                    logger.info(
+                            "Consumer topic provider registration finished; 
cycle={}, completed={}, "
+                                    + "windowChanges={}, expectedTopics={}, 
actualTopics={}, topicsConsistent={}",
+                            cycle,
+                            completed,
+                            changes,
+                            expected,
+                            actual,
+                            expected.equals(actual));
+                }
             } else {
                 logger.debug("Unregistering property provider with");
                 this.propagationService.unregister();
@@ -211,10 +258,11 @@ public class JobConsumerManager {
         } else if (enable) {
             // update properties
             synchronized (this.topicToConsumerMap) {
-                this.calculateTopics(true);
+                this.topics = this.calculateTopics(true);
             }
             logger.debug("Updating property provider with: {}", this.topics);
             
this.propagationService.setProperties(this.getRegistrationProperties());
+            logger.debug("Consumer topic provider modification completed");
         }
     }
 
@@ -333,6 +381,7 @@ public class JobConsumerManager {
         if (topics != null && topics.length > 0) {
             final ConsumerInfo info = new ConsumerInfo(serviceReference, 
isConsumer);
             boolean changed = false;
+            Object[] diagnostic;
             synchronized (this.topicToConsumerMap) {
                 for (final String t : topics) {
                     if (t != null) {
@@ -349,13 +398,21 @@ public class JobConsumerManager {
                         }
                     }
                 }
+                final boolean calculationEnabled = this.propagationService != 
null;
                 if (changed) {
-                    this.calculateTopics(this.propagationService != null);
+                    this.topics = this.calculateTopics(calculationEnabled);
                 }
+                diagnostic = this.publicationChange("bind", info.serviceId, 
topics, changed, calculationEnabled);
             }
+            logPublicationChange(diagnostic);
             if (changed && this.propagationService != null) {
                 logger.debug("Updating property provider with: {}", 
this.topics);
                 
this.propagationService.setProperties(this.getRegistrationProperties());
+                logger.debug("Consumer topic notification completed; 
operation=bind, serviceId={}", info.serviceId);
+            } else if (changed) {
+                logger.debug(
+                        "Consumer topic notification skipped; operation=bind, 
serviceId={}, reason=no-provider-handle",
+                        info.serviceId);
             }
         }
     }
@@ -370,6 +427,7 @@ public class JobConsumerManager {
         if (topics != null && topics.length > 0) {
             final ConsumerInfo info = new ConsumerInfo(serviceReference, 
isConsumer);
             boolean changed = false;
+            Object[] diagnostic;
             // Collect async callbacks to invoke outside the lock to avoid
             // lock-order inversion between topicToConsumerMap and 
QueueJobCache.cache
             final List<JobExecutionContext> asyncCallbacks = new ArrayList<>();
@@ -399,10 +457,13 @@ public class JobConsumerManager {
                         }
                     }
                 }
+                final boolean calculationEnabled = this.propagationService != 
null;
                 if (changed) {
-                    this.calculateTopics(this.propagationService != null);
+                    this.topics = this.calculateTopics(calculationEnabled);
                 }
+                diagnostic = this.publicationChange("unbind", info.serviceId, 
topics, changed, calculationEnabled);
             }
+            logPublicationChange(diagnostic);
             // notify listeners outside the lock
             for (final JobExecutionContext context : asyncCallbacks) {
                 try {
@@ -417,6 +478,11 @@ public class JobConsumerManager {
             if (changed && this.propagationService != null) {
                 logger.debug("Updating property provider with: {}", 
this.topics);
                 
this.propagationService.setProperties(this.getRegistrationProperties());
+                logger.debug("Consumer topic notification completed; 
operation=unbind, serviceId={}", info.serviceId);
+            } else if (changed) {
+                logger.debug(
+                        "Consumer topic notification skipped; 
operation=unbind, serviceId={}, reason=no-provider-handle",
+                        info.serviceId);
             }
         }
     }
@@ -430,7 +496,8 @@ public class JobConsumerManager {
         return false;
     }
 
-    private void calculateTopics(final boolean enabled) {
+    /** Calculate an advertisement without changing publication state. Caller 
holds the map lock. */
+    private String calculateTopics(final boolean enabled) {
         if (enabled) {
             // create a sorted list - this ensures that the property value
             // is always the same for the same topics.
@@ -456,9 +523,77 @@ public class JobConsumerManager {
                 }
                 sb.append(topic);
             }
-            this.topics = sb.toString();
+            return sb.toString();
         } else {
-            this.topics = null;
+            return null;
+        }
+    }
+
+    /** Capture callback state under the map lock; logging must happen outside 
it. */
+    private Object[] publicationChange(
+            final String operation,
+            final long serviceId,
+            final String[] serviceTopics,
+            final boolean changed,
+            final boolean calculationEnabled) {
+        if (this.publicationPending && changed) {
+            this.publicationWindowChanges++;
+        }
+        if (!logger.isDebugEnabled()) {
+            return null;
+        }
+        return new Object[] {
+            operation,
+            serviceId,
+            serviceTopics,
+            this.publicationCycle,
+            this.publicationPending,
+            changed,
+            changed ? calculationEnabled : null,
+            this.topics,
+            changed && !calculationEnabled
+        };
+    }
+
+    private void logPublicationChange(final Object[] diagnostic) {
+        if (diagnostic != null) {
+            logger.debug(
+                    "Consumer topic change; operation={}, serviceId={}, 
serviceTopics={}, cycle={}, "
+                            + "registrationPending={}, topicMapChanged={}, 
calculationEnabled={}, "
+                            + "resultingTopics={}, 
notificationUnavailableAtCalculation={}",
+                    diagnostic);
+        }
+    }
+
+    /**
+     * Describe local consumer availability without acquiring or instantiating 
consumer services.
+     * Publication permission is evaluated against matching consumer patterns, 
not the submitted topic.
+     */
+    public String getPublicationDiagnostics(final String topic) {
+        synchronized (this.topicToConsumerMap) {
+            final List<String> patterns = new ArrayList<>();
+            patterns.add(topic);
+            int pos = topic.lastIndexOf('/');
+            if (pos > 0) {
+                patterns.add(topic.substring(0, pos + 1) + "*");
+                do {
+                    patterns.add(topic.substring(0, pos + 1) + "**");
+                    pos = topic.lastIndexOf('/', pos - 1);
+                } while (pos > 0);
+            }
+            boolean bound = false;
+            boolean allowed = false;
+            for (final String pattern : patterns) {
+                if (this.topicToConsumerMap.containsKey(pattern)) {
+                    bound = true;
+                    allowed |= this.allowListMatchers != null
+                            && this.match(pattern, this.allowListMatchers)
+                            && (this.denyListMatchers == null || 
!this.match(pattern, this.denyListMatchers));
+                }
+            }
+            return "localConsumerBound=" + bound + ", publicationAllowed=" + 
allowed
+                    + ", publicationCycle=" + this.publicationCycle + ", 
registrationPending=" + this.publicationPending
+                    + ", registrationWindowChanges=" + 
this.publicationWindowChanges;
         }
     }
 
diff --git a/src/main/java/org/apache/sling/event/impl/jobs/JobManagerImpl.java 
b/src/main/java/org/apache/sling/event/impl/jobs/JobManagerImpl.java
index df0247c..2d89a4e 100644
--- a/src/main/java/org/apache/sling/event/impl/jobs/JobManagerImpl.java
+++ b/src/main/java/org/apache/sling/event/impl/jobs/JobManagerImpl.java
@@ -586,10 +586,7 @@ public class JobManagerImpl implements JobManager, 
EventHandler, Runnable {
         info.targetId = (caps == null ? null : caps.detectTarget(jobTopic, 
jobProperties, info));
 
         if (info.targetId == null && logger.isInfoEnabled()) {
-            logger.info(
-                    "Persisting job {} into queue {} with no assigned target",
-                    Utility.toString(jobTopic, jobProperties),
-                    info.queueName);
+            logUnassignedJob(jobTopic, info.queueName, caps);
         } else if (info.targetId != null && logger.isDebugEnabled()) {
             logger.debug(
                     "Persisting job {} into queue {}, target={}",
@@ -618,6 +615,33 @@ public class JobManagerImpl implements JobManager, 
EventHandler, Runnable {
         return null;
     }
 
+    /**
+     * Diagnose the routing decision before persistence, without exposing 
potentially sensitive job
+     * properties.
+     */
+    private void logUnassignedJob(final String jobTopic, final String 
queueName, final TopologyCapabilities caps) {
+        logger.info(
+                "Persisting job [topic={}] into queue {} with no assigned 
target; reason={}, instanceId={}, "
+                        + "readiness={}, capabilitiesActive={}, 
viewCurrent={}, leader={}, capabilitiesChanged={}, "
+                        + "lastTopologyEventTime={}, localTopics={}, 
localInstanceAdvertised={}, localPublication=[{}]",
+                jobTopic,
+                queueName,
+                caps == null ? "no-topology" : "no-matching-consumer",
+                Environment.APPLICATION_ID,
+                this.configuration.isJobProcessingEnabled(),
+                caps == null ? null : caps.isActive(),
+                caps == null ? null : caps.isCurrent(),
+                caps == null ? null : caps.isLeader(),
+                caps != this.configuration.getTopologyCapabilities(),
+                this.configuration.getLastTopologyEventTime(),
+                this.jobConsumerManager.getTopics(),
+                caps == null
+                        ? null
+                        : caps.getPotentialTargets(jobTopic).stream()
+                                .anyMatch(target -> 
target.getSlingId().equals(Environment.APPLICATION_ID)),
+                this.jobConsumerManager.getPublicationDiagnostics(jobTopic));
+    }
+
     /**
      * Write a job to the resource tree.
      * @param resolver The resolver resolver
diff --git 
a/src/main/java/org/apache/sling/event/impl/jobs/config/JobManagerConfiguration.java
 
b/src/main/java/org/apache/sling/event/impl/jobs/config/JobManagerConfiguration.java
index 638d74c..3d4c4bb 100644
--- 
a/src/main/java/org/apache/sling/event/impl/jobs/config/JobManagerConfiguration.java
+++ 
b/src/main/java/org/apache/sling/event/impl/jobs/config/JobManagerConfiguration.java
@@ -237,6 +237,9 @@ public class JobManagerConfiguration {
      */
     private volatile TopologyCapabilities topologyCapabilities;
 
+    /** Last successful event-handler completion, distinct from discovery 
delivery or delayed maintenance. */
+    private volatile long lastTopologyEventTime;
+
     /**
      * External readiness signal (e.g. from a Kubernetes readiness probe via 
an OSGi Condition
      * service). When {@code null}, job processing is paused but the topology 
state is preserved.
@@ -439,6 +442,16 @@ public class JobManagerConfiguration {
         return this.topologyCapabilities;
     }
 
+    /**
+     * Get the completion time of the last successfully handled topology event.
+     * A startup-delayed event is not counted until forwarded and handled; 
maintenance scheduled
+     * by that handler may still be pending.
+     * @return Epoch milliseconds, or zero if no event has completed yet.
+     */
+    public long getLastTopologyEventTime() {
+        return this.lastTopologyEventTime;
+    }
+
     public QueueConfigurationManager getQueueConfigurationManager() {
         return this.queueConfigManager;
     }
@@ -729,6 +742,8 @@ public class JobManagerConfiguration {
 
             this.startProcessing(eventType, new 
TopologyCapabilities(event.getNewView(), this));
         }
+        // Leave the previous timestamp intact if handling fails, rather than 
suggesting successful progress.
+        this.lastTopologyEventTime = System.currentTimeMillis();
     }
 
     /**
diff --git 
a/src/main/java/org/apache/sling/event/impl/jobs/config/TopologyCapabilities.java
 
b/src/main/java/org/apache/sling/event/impl/jobs/config/TopologyCapabilities.java
index f338716..86f0b3a 100644
--- 
a/src/main/java/org/apache/sling/event/impl/jobs/config/TopologyCapabilities.java
+++ 
b/src/main/java/org/apache/sling/event/impl/jobs/config/TopologyCapabilities.java
@@ -173,7 +173,17 @@ public class TopologyCapabilities {
      * @return {@code true} if still active.
      */
     public boolean isActive() {
-        return this.active && this.jobManagerConfiguration.isActive() && 
this.view.isCurrent();
+        return this.active && this.jobManagerConfiguration.isActive() && 
this.isCurrent();
+    }
+
+    /**
+     * Whether the discovery view used to build these capabilities is still 
current.
+     * This can remain true after local deactivation; unlike {@link 
#isActive()}, it checks only
+     * the discovery view so diagnostics can distinguish the two states.
+     * @return {@code true} if the view is current.
+     */
+    public boolean isCurrent() {
+        return this.view.isCurrent();
     }
 
     /**
diff --git 
a/src/test/java/org/apache/sling/event/impl/jobs/JobConsumerManagerTest.java 
b/src/test/java/org/apache/sling/event/impl/jobs/JobConsumerManagerTest.java
index c605d82..89fef08 100644
--- a/src/test/java/org/apache/sling/event/impl/jobs/JobConsumerManagerTest.java
+++ b/src/test/java/org/apache/sling/event/impl/jobs/JobConsumerManagerTest.java
@@ -19,7 +19,13 @@
 package org.apache.sling.event.impl.jobs;
 
 import java.lang.annotation.Annotation;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
 
+import org.apache.sling.discovery.PropertyProvider;
+import org.apache.sling.event.impl.TestUtil;
+import org.apache.sling.event.impl.jobs.config.TopologyCapabilities;
 import org.apache.sling.event.jobs.consumer.JobConsumer;
 import org.apache.sling.event.jobs.consumer.JobExecutor;
 import org.junit.Test;
@@ -27,10 +33,14 @@ import org.mockito.Mockito;
 import org.osgi.framework.BundleContext;
 import org.osgi.framework.Constants;
 import org.osgi.framework.ServiceReference;
+import org.osgi.framework.ServiceRegistration;
+import org.slf4j.Logger;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
 
 public class JobConsumerManagerTest {
 
@@ -247,4 +257,115 @@ public class JobConsumerManagerTest {
         jcs.unbindJobExecutor(ref3);
         assertEquals(jc4, jcs.getExecutor("a/b"));
     }
+
+    @Test
+    public void 
testRegistrationDiagnosticsObserveLostPublicationWithoutRepairingIt() throws 
Exception {
+        final BundleContext context = Mockito.mock(BundleContext.class);
+        final JobConsumerManager manager = new JobConsumerManager();
+        final Logger logger = Mockito.mock(Logger.class);
+        Mockito.when(logger.isDebugEnabled()).thenReturn(true);
+        TestUtil.setFieldValue(manager, "logger", logger);
+        final ServiceRegistration<?> registration = 
Mockito.mock(ServiceRegistration.class);
+        manager.bindJobExecutor(executorReference("a/existing", 1L));
+        final ServiceReference<JobExecutor> arriving = 
executorReference("b/arriving", 2L);
+        final ExecutorService worker = Executors.newSingleThreadExecutor();
+        try {
+            Mockito.when(context.registerService(
+                            Mockito.eq(PropertyProvider.class), 
Mockito.any(PropertyProvider.class), Mockito.any()))
+                    .thenAnswer(invocation -> {
+                        final PropertyProvider provider = 
invocation.getArgument(1);
+                        assertEquals("a/existing", 
provider.getProperty(TopologyCapabilities.PROPERTY_TOPICS));
+                        // Keep registration open until a different thread has 
completed the binding.
+                        worker.submit(() -> 
manager.bindJobExecutor(arriving)).get(5, TimeUnit.SECONDS);
+                        assertTrue(
+                                
manager.getPublicationDiagnostics("b/arriving").contains("registrationPending=true"));
+                        
assertNull(provider.getProperty(TopologyCapabilities.PROPERTY_TOPICS));
+                        return registration;
+                    });
+
+            manager.activate(context, getDefaultConfig(), 
getDeprecatedConfig());
+
+            assertNull(manager.getTopics());
+            final String state = 
manager.getPublicationDiagnostics("b/arriving");
+            assertTrue(state.contains("localConsumerBound=true"));
+            assertTrue(state.contains("publicationAllowed=true"));
+            assertTrue(state.contains("registrationPending=false"));
+            assertTrue(state.contains("registrationWindowChanges=1"));
+            Mockito.verify(logger)
+                    .info(
+                            "Consumer topic provider registration finished; 
cycle={}, completed={}, "
+                                    + "windowChanges={}, expectedTopics={}, 
actualTopics={}, topicsConsistent={}",
+                            1L,
+                            true,
+                            1,
+                            "a/existing,b/arriving",
+                            null,
+                            false);
+            Mockito.verify(registration, 
Mockito.never()).setProperties(Mockito.any());
+            Mockito.verify(context, Mockito.never()).getService(Mockito.any());
+        } finally {
+            worker.shutdownNow();
+            assertTrue(worker.awaitTermination(5, TimeUnit.SECONDS));
+        }
+    }
+
+    @Test
+    public void testPublicationDiagnosticsApplyFiltersToConsumerPatterns() {
+        final JobConsumerManager manager = new JobConsumerManager();
+        final BundleContext context = Mockito.mock(BundleContext.class);
+        Mockito.when(context.registerService(
+                        Mockito.eq(PropertyProvider.class), 
Mockito.any(PropertyProvider.class), Mockito.any()))
+                .thenAnswer(invocation -> 
Mockito.mock(ServiceRegistration.class));
+        final JobConsumerManager.Config config = 
Mockito.spy(getDefaultConfig());
+        Mockito.when(config.job_consumermanager_denylist()).thenReturn(new 
String[] {"blocked/*"});
+        manager.activate(context, config, getDeprecatedConfig());
+        manager.bindJobExecutor(executorReference("allowed/*", 1L));
+        manager.bindJobExecutor(executorReference("blocked/**", 2L));
+
+        
assertTrue(manager.getPublicationDiagnostics("allowed/job").contains("localConsumerBound=true"));
+        
assertTrue(manager.getPublicationDiagnostics("allowed/job").contains("publicationAllowed=true"));
+        
assertTrue(manager.getPublicationDiagnostics("blocked/deep/job").contains("localConsumerBound=true"));
+        
assertTrue(manager.getPublicationDiagnostics("blocked/deep/job").contains("publicationAllowed=false"));
+        
assertTrue(manager.getPublicationDiagnostics("allowed/deep/job").contains("localConsumerBound=false"));
+        Mockito.verify(context, Mockito.never()).getService(Mockito.any());
+    }
+
+    @Test
+    public void testRegistrationFailureIsReportedAndPropagated() {
+        final JobConsumerManager manager = new JobConsumerManager();
+        final Logger logger = Mockito.mock(Logger.class);
+        TestUtil.setFieldValue(manager, "logger", logger);
+        final BundleContext context = Mockito.mock(BundleContext.class);
+        final IllegalStateException failure = new 
IllegalStateException("Registration failed");
+        Mockito.when(context.registerService(
+                        Mockito.eq(PropertyProvider.class), 
Mockito.any(PropertyProvider.class), Mockito.any()))
+                .thenThrow(failure);
+
+        try {
+            manager.activate(context, getDefaultConfig(), 
getDeprecatedConfig());
+            fail("Registration failure must propagate");
+        } catch (final IllegalStateException actual) {
+            assertTrue(actual == failure);
+        }
+
+        
assertTrue(manager.getPublicationDiagnostics("missing/job").contains("registrationPending=false"));
+        Mockito.verify(logger)
+                .info(
+                        "Consumer topic provider registration finished; 
cycle={}, completed={}, "
+                                + "windowChanges={}, expectedTopics={}, 
actualTopics={}, topicsConsistent={}",
+                        1L,
+                        false,
+                        0,
+                        "",
+                        "",
+                        true);
+    }
+
+    @SuppressWarnings("unchecked")
+    private ServiceReference<JobExecutor> executorReference(final String 
topic, final long id) {
+        final ServiceReference<JobExecutor> reference = 
Mockito.mock(ServiceReference.class);
+        
Mockito.when(reference.getProperty(JobExecutor.PROPERTY_TOPICS)).thenReturn(topic);
+        
Mockito.when(reference.getProperty(Constants.SERVICE_ID)).thenReturn(id);
+        return reference;
+    }
 }
diff --git 
a/src/test/java/org/apache/sling/event/impl/jobs/JobManagerImplTest.java 
b/src/test/java/org/apache/sling/event/impl/jobs/JobManagerImplTest.java
index 34162d6..f961478 100644
--- a/src/test/java/org/apache/sling/event/impl/jobs/JobManagerImplTest.java
+++ b/src/test/java/org/apache/sling/event/impl/jobs/JobManagerImplTest.java
@@ -22,16 +22,28 @@ import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 import java.io.PrintStream;
 import java.lang.reflect.InvocationTargetException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
 
 import org.apache.commons.lang3.reflect.FieldUtils;
 import org.apache.sling.api.resource.Resource;
 import org.apache.sling.api.resource.ResourceResolver;
+import org.apache.sling.discovery.InstanceDescription;
 import org.apache.sling.event.impl.TestUtil;
 import org.apache.sling.event.impl.jobs.config.InternalQueueConfiguration;
 import org.apache.sling.event.impl.jobs.config.JobManagerConfiguration;
 import org.apache.sling.event.impl.jobs.config.QueueConfigurationManager;
 import 
org.apache.sling.event.impl.jobs.config.QueueConfigurationManager.QueueInfo;
 import org.apache.sling.event.impl.jobs.config.TopologyCapabilities;
+import org.apache.sling.event.impl.support.Environment;
+import org.apache.sling.event.jobs.Job;
 import org.apache.sling.event.jobs.JobManager.QueryType;
 import org.junit.After;
 import org.junit.Before;
@@ -40,6 +52,7 @@ import org.slf4j.Logger;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyString;
@@ -57,6 +70,7 @@ public class JobManagerImplTest {
     private PrintStream originalErr;
     private ByteArrayOutputStream outContent;
     private JobManagerConfiguration configuration;
+    private JobConsumerManager consumerManager;
 
     private static final int LEVEL_DEBUG = 10;
     private static final int LEVEL_INFO = 20;
@@ -73,7 +87,12 @@ public class JobManagerImplTest {
         QueueConfigurationManager queueConfigMgr = 
mock(QueueConfigurationManager.class);
         this.info = new QueueInfo();
         info.queueConfiguration = mock(InternalQueueConfiguration.class);
-        when(queueConfigMgr.getQueueInfo(anyString())).thenReturn(info);
+        when(queueConfigMgr.getQueueInfo(anyString())).thenAnswer(invocation 
-> {
+            QueueInfo result = new QueueInfo();
+            result.queueConfiguration = info.queueConfiguration;
+            result.queueName = info.queueName;
+            return result;
+        });
         
when(configuration.getQueueConfigurationManager()).thenReturn(queueConfigMgr);
 
         this.capabilities = mock(TopologyCapabilities.class);
@@ -85,6 +104,8 @@ public class JobManagerImplTest {
         
when(resolver.getResource(anyString())).thenReturn(mock(Resource.class));
         when(configuration.createResourceResolver()).thenReturn(resolver);
 
+        this.consumerManager = mock(JobConsumerManager.class);
+
         this.outContent = new ByteArrayOutputStream();
         this.originalErr = System.err;
         System.setErr(new PrintStream(outContent));
@@ -115,14 +136,12 @@ public class JobManagerImplTest {
         jobManager.addJob("not/assigned", null, null);
         assertFalse(TestUtil.containsLine(
                 this.outContent,
-                line -> line.contains(
-                        "Persisting job Sling Job [topic=not/assigned] into 
queue null with no assigned target")));
+                line -> line.contains("Persisting job [topic=not/assigned] 
into queue null with no assigned target")));
 
         jobManager.addJob("is/assigned", null, null);
         assertFalse(TestUtil.containsLine(
                 this.outContent,
-                line -> line.contains(
-                        "Persisting job Sling Job [topic=is/assigned] into 
queue null with no assigned target")));
+                line -> line.contains("Persisting job [topic=is/assigned] into 
queue null with no assigned target")));
     }
 
     @Test
@@ -133,14 +152,138 @@ public class JobManagerImplTest {
         jobManager.addJob("not/assigned", null, null);
         assertTrue(TestUtil.containsLine(
                 this.outContent,
-                line -> line.contains(
-                        "Persisting job Sling Job [topic=not/assigned] into 
queue null with no assigned target")));
+                line -> line.contains("Persisting job [topic=not/assigned] 
into queue null with no assigned target")));
 
         jobManager.addJob("is/assigned", null, null);
-        assertTrue(TestUtil.containsLine(
+        assertFalse(TestUtil.containsLine(
                 this.outContent,
-                line -> !line.contains(
-                        "Persisting job Sling Job [topic=is/assigned] into 
queue null with no assigned target")));
+                line -> line.contains("Persisting job [topic=is/assigned] into 
queue null with no assigned target")));
+    }
+
+    @Test
+    public void logsMissingTopologyWithoutJobProperties() throws Exception {
+        JobManagerImpl jobManager = getJobManager(LEVEL_INFO);
+        when(configuration.getTopologyCapabilities()).thenReturn(null);
+        when(configuration.isJobProcessingEnabled()).thenReturn(true);
+        when(configuration.getLastTopologyEventTime()).thenReturn(1234L);
+        when(consumerManager.getTopics()).thenReturn("common/core/email");
+
+        assertNotNull(
+                jobManager.addJob("common/core/email", 
Collections.singletonMap("body", "private-mail-body"), null));
+
+        assertTrue(TestUtil.containsLine(
+                outContent,
+                line -> line.contains("reason=no-topology")
+                        && line.contains("readiness=true")
+                        && line.contains("capabilitiesActive=null")
+                        && line.contains("viewCurrent=null")
+                        && line.contains("lastTopologyEventTime=1234")
+                        && line.contains("localTopics=common/core/email")));
+        assertFalse(outContent.toString().contains("private-mail-body"));
+    }
+
+    @Test
+    public void logsMissingConsumerWithCapabilityState() throws Exception {
+        JobManagerImpl jobManager = getJobManager(LEVEL_INFO);
+        when(capabilities.isActive()).thenReturn(false);
+        when(capabilities.isCurrent()).thenReturn(false);
+        when(capabilities.isLeader()).thenReturn(true);
+        
when(consumerManager.getTopics()).thenReturn("common/core/email,other/**");
+        when(consumerManager.getPublicationDiagnostics("common/core/email"))
+                .thenReturn("localConsumerBound=true, publicationAllowed=true, 
registrationPending=false");
+
+        assertNotNull(jobManager.addJob("common/core/email", null, null));
+
+        assertTrue(TestUtil.containsLine(
+                outContent,
+                line -> line.contains("reason=no-matching-consumer")
+                        && line.contains("readiness=false")
+                        && line.contains("capabilitiesActive=false")
+                        && line.contains("viewCurrent=false")
+                        && line.contains("leader=true")
+                        && line.contains("capabilitiesChanged=false")
+                        && 
line.contains("localTopics=common/core/email,other/**")
+                        && line.contains("localInstanceAdvertised=false")
+                        && line.contains(
+                                "localConsumerBound=true, 
publicationAllowed=true, registrationPending=false")));
+    }
+
+    @Test
+    public void logsCapabilityReplacementDuringRouting() throws Exception {
+        JobManagerImpl jobManager = getJobManager(LEVEL_INFO);
+        when(configuration.getTopologyCapabilities()).thenReturn(capabilities, 
mock(TopologyCapabilities.class));
+
+        jobManager.addJob("not/assigned", null, null);
+
+        assertTrue(TestUtil.containsLine(outContent, line -> 
line.contains("capabilitiesChanged=true")));
+    }
+
+    @Test
+    public void logsLocalAdvertisementSeparatelyFromRemoteConsumers() throws 
Exception {
+        final String originalId = Environment.APPLICATION_ID;
+        try {
+            Environment.APPLICATION_ID = "diagnostic-local";
+            final JobManagerImpl jobManager = getJobManager(LEVEL_INFO);
+            final InstanceDescription remote = mock(InstanceDescription.class);
+            when(remote.getSlingId()).thenReturn("diagnostic-remote");
+            
when(capabilities.getPotentialTargets("not/assigned")).thenReturn(Collections.singletonList(remote));
+
+            assertNotNull(jobManager.addJob("not/assigned", null, null));
+            assertTrue(TestUtil.containsLine(outContent, line -> 
line.contains("localInstanceAdvertised=false")));
+
+            outContent.reset();
+            final InstanceDescription local = mock(InstanceDescription.class);
+            when(local.getSlingId()).thenReturn("diagnostic-local");
+            
when(capabilities.getPotentialTargets("not/assigned")).thenReturn(Arrays.asList(remote,
 local));
+
+            assertNotNull(jobManager.addJob("not/assigned", null, null));
+            assertTrue(TestUtil.containsLine(outContent, line -> 
line.contains("localInstanceAdvertised=true")));
+        } finally {
+            Environment.APPLICATION_ID = originalId;
+        }
+    }
+
+    @Test
+    public void logsEveryUnassignedSubmission() throws Exception {
+        JobManagerImpl jobManager = getJobManager(LEVEL_INFO);
+        assertNotNull(jobManager.addJob("not/assigned", null, null));
+        assertEquals(1, countUnassignedMessages());
+
+        when(consumerManager.getTopics()).thenReturn("new/consumer");
+        assertNotNull(jobManager.addJob("not/assigned", null, null));
+        assertEquals(2, countUnassignedMessages());
+        assertTrue(TestUtil.containsLine(outContent, line -> 
line.contains("localTopics=new/consumer")));
+
+        assertNotNull(jobManager.addJob("other/topic", null, null));
+        assertEquals(3, countUnassignedMessages());
+    }
+
+    @Test
+    public void logsEveryConcurrentUnassignedSubmission() throws Exception {
+        JobManagerImpl jobManager = getJobManager(LEVEL_INFO);
+        ExecutorService executor = Executors.newFixedThreadPool(8);
+        CountDownLatch ready = new CountDownLatch(8);
+        CountDownLatch start = new CountDownLatch(1);
+        List<Future<Job>> submissions = new ArrayList<>();
+        try {
+            for (int i = 0; i < 8; i++) {
+                submissions.add(executor.submit(() -> {
+                    ready.countDown();
+                    assertTrue(start.await(5, TimeUnit.SECONDS));
+                    return jobManager.addJob("not/assigned", null, null);
+                }));
+            }
+            assertTrue(ready.await(5, TimeUnit.SECONDS));
+            start.countDown();
+            for (Future<Job> submission : submissions) {
+                assertNotNull(submission.get(5, TimeUnit.SECONDS));
+            }
+            assertEquals(8, countUnassignedMessages());
+        } finally {
+            start.countDown();
+            executor.shutdownNow();
+            assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS));
+        }
     }
 
     @Test
@@ -171,6 +314,13 @@ public class JobManagerImplTest {
         FieldUtils.writeDeclaredField(logger, "currentLogLevel", level, true);
 
         FieldUtils.writeDeclaredField(jobManager, "configuration", 
configuration, true);
+        FieldUtils.writeDeclaredField(jobManager, "jobConsumerManager", 
consumerManager, true);
         return jobManager;
     }
+
+    private long countUnassignedMessages() {
+        return Arrays.stream(outContent.toString().split("\n"))
+                .filter(line -> line.contains("with no assigned target"))
+                .count();
+    }
 }
diff --git 
a/src/test/java/org/apache/sling/event/impl/jobs/config/JobManagerConfigurationTest.java
 
b/src/test/java/org/apache/sling/event/impl/jobs/config/JobManagerConfigurationTest.java
index 5b150bd..8a2e8b7 100644
--- 
a/src/test/java/org/apache/sling/event/impl/jobs/config/JobManagerConfigurationTest.java
+++ 
b/src/test/java/org/apache/sling/event/impl/jobs/config/JobManagerConfigurationTest.java
@@ -98,6 +98,27 @@ public class JobManagerConfigurationTest {
         return config;
     }
 
+    @Test
+    public void testLastTopologyEventTimeTracksCompletedEvents() {
+        final JobManagerConfiguration config = Mockito.spy(new 
JobManagerConfiguration());
+        assertEquals(0, config.getLastTopologyEventTime());
+
+        final long before = System.currentTimeMillis();
+        config.doHandleTopologyEvent(new 
TopologyEvent(TopologyEvent.Type.TOPOLOGY_INIT, null, createView()));
+        final long completedAt = config.getLastTopologyEventTime();
+        assertTrue(completedAt >= before);
+        assertTrue(completedAt <= System.currentTimeMillis());
+
+        Mockito.doThrow(new IllegalStateException("resolver unavailable"))
+                .when(config)
+                .createResourceResolver();
+        assertThrows(
+                IllegalStateException.class,
+                () -> config.doHandleTopologyEvent(
+                        new TopologyEvent(TopologyEvent.Type.TOPOLOGY_INIT, 
null, createView())));
+        assertEquals(completedAt, config.getLastTopologyEventTime());
+    }
+
     @Test
     public void testConditionTogglePreservesTopology() throws Exception {
         final ChangeListener ccl = new ChangeListener();
diff --git a/src/test/java/org/apache/sling/event/it/JobHandlingIT.java 
b/src/test/java/org/apache/sling/event/it/JobHandlingIT.java
index 5144aa3..6cf37c9 100644
--- a/src/test/java/org/apache/sling/event/it/JobHandlingIT.java
+++ b/src/test/java/org/apache/sling/event/it/JobHandlingIT.java
@@ -443,8 +443,11 @@ public class JobHandlingIT extends AbstractJobHandlingIT {
             assertEquals(JobState.QUEUED, job.getJobState());
 
             Predicate<String> matcher = (line) -> line.contains(
-                    "Persisting job Sling Job [topic=no/consumer/registered] 
into queue <main queue> with no assigned target");
-            assertTrue(TestUtil.containsLine(outContent, matcher));
+                            "Persisting job [topic=no/consumer/registered] 
into queue <main queue> with no assigned target")
+                    && line.contains("reason=no-matching-consumer");
+            assertTrue(
+                    "Missing unassigned-job diagnostic. Captured output:\n" + 
outContent,
+                    TestUtil.containsLine(outContent, matcher));
 
         } finally {
             System.setOut(originalOut);

Reply via email to