Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
v5.1.21
------
* Add `Engine.getActivePlanCount()` and opt-in `Engine.getActivePlans()` and `Engine.getOldestActivePlanAge()` for active-plan observability (`_TrackActivePlans_`, off by default).

v5.1.20
------
* Upgrade bytebuddy and asm version for JDK 17 and JDK 21 support
Expand Down
2 changes: 1 addition & 1 deletion gradle.properties
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
version=5.1.20
version=5.1.21
group=com.linkedin.parseq
org.gradle.parallel=true
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,10 @@ public Thread newThread(Runnable r) {
final EngineBuilder builder = new EngineBuilder().setTaskExecutor(scheduler).setTimerScheduler(scheduler);
builder.setPlanDeactivationListener(_batchingSupport);
builder.setEngineProperty(Engine.MAX_CONCURRENT_PLANS, config.CONCURRENCY_LEVEL);
// Enable with -Dparseq.benchmark.trackActivePlans=true to measure the overhead of active plan tracking.
if (Boolean.getBoolean("parseq.benchmark.trackActivePlans")) {
builder.setEngineProperty(Engine.TRACK_ACTIVE_PLANS, true);
}
final Engine engine = builder.build();
try {
doRunBenchmark(engine, config);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/*
* Copyright 2026 LinkedIn, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

package com.linkedin.parseq;

import com.linkedin.parseq.internal.ArgumentUtil;
import java.util.concurrent.TimeUnit;


/**
* An immutable snapshot of a plan that has been started by an {@link Engine} and has not completed yet.
* Returned by {@link Engine#getActivePlans()}.
*/
public final class ActivePlanInfo {
private final long _planId;
private final String _planClass;
private final String _rootTaskName;
private final long _startNanos;
private final long _snapshotNanos;

ActivePlanInfo(long planId, String planClass, String rootTaskName, long startNanos, long snapshotNanos) {
_planId = planId;
_planClass = planClass;
_rootTaskName = rootTaskName;
_startNanos = startNanos;
_snapshotNanos = snapshotNanos;
}

ActivePlanInfo at(long snapshotNanos) {
return new ActivePlanInfo(_planId, _planClass, _rootTaskName, _startNanos, snapshotNanos);
}

/** Returns the plan id, which is also the id used in the plan's trace. */
public long getPlanId() {
return _planId;
}

/** Returns the plan class the plan was started with. */
public String getPlanClass() {
return _planClass;
}

/** Returns the name of the plan's root task as it was when the plan started. */
public String getRootTaskName() {
return _rootTaskName;
}

/** Returns how long the plan had been running when the snapshot was taken. */
public long getAge(TimeUnit unit) {
ArgumentUtil.requireNotNull(unit, "unit");
return unit.convert(ageNanosAt(_snapshotNanos), TimeUnit.NANOSECONDS);
}

long ageNanosAt(long nowNanos) {
return Math.max(0L, nowNanos - _startNanos);
}

@Override
public String toString() {
return "ActivePlanInfo{planId=" + _planId + ", planClass=" + _planClass + ", rootTaskName=" + _rootTaskName
+ ", ageMs=" + getAge(TimeUnit.MILLISECONDS) + "}";
}
}
160 changes: 140 additions & 20 deletions subprojects/parseq/src/main/java/com/linkedin/parseq/Engine.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,12 @@
package com.linkedin.parseq;

import com.linkedin.parseq.internal.PlanBasedRateLimiter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.OptionalLong;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Semaphore;
Expand Down Expand Up @@ -65,6 +70,13 @@ public class Engine {

public static final String DEFAULT_TASK_QUEUE = "_DefaultTaskQueue_";

/**
* Enables {@link #getActivePlans()} and {@link #getOldestActivePlanAge(TimeUnit)}.
* Off by default; {@link #getActivePlanCount()} works regardless of this setting.
*/
public static final String TRACK_ACTIVE_PLANS = "_TrackActivePlans_";
private static final boolean DEFAULT_TRACK_ACTIVE_PLANS = false;

private static final State INIT = new State(StateName.RUN, 0);
private static final State TERMINATED = new State(StateName.TERMINATED, 0);
private static final Logger LOG = LoggerFactory.getLogger(LOGGER_BASE);
Expand Down Expand Up @@ -122,6 +134,9 @@ private static enum StateName {

private final ExecutionMonitor _executionMonitor;

// Null unless TRACK_ACTIVE_PLANS is enabled.
private final ConcurrentHashMap<Long, ActivePlanInfo> _activePlans;

private final PlanDeactivationListener _planDeactivationListener;
private final PlanCompletionListener _planCompletionListener;

Expand Down Expand Up @@ -168,25 +183,15 @@ private static enum StateName {
_drainSerialExecutorQueue = DEFAULT_DRAIN_SERIAL_EXECUTOR_QUEUE;
}

_taskDoneListener = resolvedPromise -> {
assert _stateRef.get()._pendingCount > 0;
assert _stateRef.get()._stateName != StateName.TERMINATED;

State currState;
State newState;
do {
currState = _stateRef.get();
newState = new State(currState._stateName, currState._pendingCount - 1);
} while (!_stateRef.compareAndSet(currState, newState));

_concurrentPlans.release();
if (planClassRateLimiter != null) {
_planBasedRateLimiter.release(resolvedPromise.getPlanClass());
}
final boolean trackActivePlans = _properties.containsKey(TRACK_ACTIVE_PLANS)
? (Boolean) getProperty(TRACK_ACTIVE_PLANS) : DEFAULT_TRACK_ACTIVE_PLANS;
_activePlans = trackActivePlans ? new ConcurrentHashMap<>() : null;

if (newState._stateName == StateName.SHUTDOWN && newState._pendingCount == 0) {
tryTransitionTerminate();
_taskDoneListener = planContext -> {
if (_activePlans != null) {
_activePlans.remove(planContext.getId());
}
releasePlan(planContext.getPlanClass());
};

_planCompletionListener = planContext -> {
Expand Down Expand Up @@ -460,12 +465,127 @@ private void runWithPermit(final Task<?> task, final String planClass) {
newState = new State(StateName.RUN, currState._pendingCount + 1);
} while (!_stateRef.compareAndSet(currState, newState));

PlanContext planContext = new PlanContext(this, _taskExecutor, _timerExecutor, _loggerFactory, _allLogger,
_rootLogger, planClass, task, _maxRelationshipsPerTrace, _planDeactivationListener, _planCompletionListener,
_taskQueueFactory.newTaskQueue(), _drainSerialExecutorQueue, _executionMonitor);
final TrackedPlanCompletion trackedCompletion = _activePlans == null ? null : new TrackedPlanCompletion();
final long startNanos = trackedCompletion == null ? 0 : System.nanoTime();
final String taskName;
final PlanContext planContext;
try {
taskName = trackedCompletion == null ? null : activePlanTaskName(task);
planContext = new PlanContext(this, _taskExecutor, _timerExecutor, _loggerFactory, _allLogger,
_rootLogger, planClass, task, _maxRelationshipsPerTrace, _planDeactivationListener,
trackedCompletion == null ? _planCompletionListener : trackedCompletion,
_taskQueueFactory.newTaskQueue(), _drainSerialExecutorQueue, _executionMonitor);
} catch (RuntimeException | Error e) {
if (trackedCompletion != null && trackedCompletion.claimCompletion()) {
releasePlan(planClass);
}
throw e;
}
if (trackedCompletion != null) {
trackedCompletion.register(planContext, taskName, startNanos);
}
new ContextImpl(planContext, task).runTask();
}

private final class TrackedPlanCompletion implements PlanCompletionListener {
private boolean _completionClaimed;

// Completion may be claimed during PlanContext construction, before its ID is available to Engine.
private synchronized void register(PlanContext planContext, String taskName, long startNanos) {
if (!_completionClaimed) {
Long planId = planContext.getId();
_activePlans.put(planId, new ActivePlanInfo(planId, planContext.getPlanClass(), taskName, startNanos,
startNanos));
}
}

private synchronized boolean claimCompletion() {
if (_completionClaimed) {
return false;
}
_completionClaimed = true;
return true;
}

@Override
public void onPlanCompleted(PlanContext planContext) {
if (claimCompletion()) {
_planCompletionListener.onPlanCompleted(planContext);
}
}
}

private static String activePlanTaskName(Task<?> task) {
try {
return task.getName();
} catch (RuntimeException e) {
LOG.debug("Unable to read active plan root task name", e);
return task.getClass().getName();
}
}

private void releasePlan(String planClass) {
assert _stateRef.get()._pendingCount > 0;
assert _stateRef.get()._stateName != StateName.TERMINATED;

State currState;
State newState;
do {
currState = _stateRef.get();
newState = new State(currState._stateName, currState._pendingCount - 1);
} while (!_stateRef.compareAndSet(currState, newState));

_concurrentPlans.release();
if (_planBasedRateLimiter != null) {
_planBasedRateLimiter.release(planClass);
}
if (newState._stateName == StateName.SHUTDOWN && newState._pendingCount == 0) {
tryTransitionTerminate();
}
}

/**
* Returns the number of plans that have been started and have not completed yet. Always available and
* cheap: it reads the counter the engine already maintains for shutdown.
*/
public long getActivePlanCount() {
return _stateRef.get()._pendingCount;
}

/**
* Returns the best-effort age of the oldest active plan, or zero when no plans are active.
* Returns empty when {@value #TRACK_ACTIVE_PLANS} is disabled. Scans the registry without copying plans.
*/
public OptionalLong getOldestActivePlanAge(TimeUnit unit) {
ArgumentUtil.requireNotNull(unit, "unit");
if (_activePlans == null) {
return OptionalLong.empty();
}
final long now = System.nanoTime();
long oldestAgeNanos = 0;
for (ActivePlanInfo plan : _activePlans.values()) {
oldestAgeNanos = Math.max(oldestAgeNanos, plan.ageNanosAt(now));
}
return OptionalLong.of(unit.convert(oldestAgeNanos, TimeUnit.NANOSECONDS));
}

/**
* Returns an unmodifiable snapshot of the plans that have not completed yet, or an empty list when
* {@value #TRACK_ACTIVE_PLANS} is not enabled. The list is not ordered and may be slightly out of date
* relative to {@link #getActivePlanCount()}.
*/
public List<ActivePlanInfo> getActivePlans() {
if (_activePlans == null) {
return Collections.emptyList();
}
final long now = System.nanoTime();
final List<ActivePlanInfo> snapshot = new ArrayList<>(_activePlans.size());
for (ActivePlanInfo plan : _activePlans.values()) {
snapshot.add(plan.at(now));
}
return Collections.unmodifiableList(snapshot);
}

// acquire a permit to run the given task plan. always acquire a permit first from engine level
// rate limiter and then from plan class level rate limit if specified.
private boolean tryAcquirePermit(String planClass) {
Expand Down
Loading
Loading