cs1302-tracer 4.3.2-SNAPSHOT API
Embed Java execution tracing in your application with cs1302-tracer. Submit Java source with optional binary dependencies, discover executable breakpoints, or process batch jobs, and receive Python Tutor or modern JSON output.
Using the Java API
Choose an entry point
Tracer.trace: execute one request and receive a detachedTraceOutcome. The call owns source preparation and guest cleanup; callers do not close the outcome. Calls may run concurrently from multiple threads in one JVM; each call is independent and launches its own guest.Tracer.discoverBreakpoints: compile submitted sources and discover executable locations without launching a guest. Inspect both returned locations and preparation diagnostics. Concurrent discovery calls are likewise independent.BatchTracer: process NDJSON request streams through reusable workers. Use try-with-resources, run oneprocessStreamcall at a time per processor, and retain ownership of input/output streams.App: invoke the process-facing command line. CLI commands run environment preflight, and some command failures terminate the calling JVM. Embedding applications useTracerorBatchTracer.
Trusted inspection exposes selected stored components of supported java.time value objects,
including dates, times, and durations, without invoking their methods. Field-only inspection retains raw
instance fields; multithread capture always uses field-only inspection. Both JSON formats preserve
object references and component primitive types.
Trusted set inspection invokes toArray() and preserves the returned element order and references.
Unmodifiable set views retain their wrapper identities and reflect backing changes in later snapshots.
A guest exception or null array result uses the ordinary fallback for the inspected object.
These collection calls pause reader observation; input they consume can be absent from the logical input cursor.
Field-only and multithread capture inspect raw storage without these collection calls.
The separate Maven launcher plugin resolves this library and starts
App in a child JVM. It supports CLI use without a caller POM;
its process management is outside the tracing Java API.
Requirements and resource ownership
Use a full JDK 21 or later and the tracer's runtime dependencies. The regular library JAR
requires those dependencies on the application class path. Submitted language features depend on the
active JDK and parser support. Java tracing calls use the running JDK and do not run the CLI's
JAVA_HOME/PATH preflight.
SourceBundle owns captured source text independently of the original files.
TraceClassPath records dependency selections without opening files;
borrowed dependencies must remain available and unchanged until tracing or discovery returns.
Each operation owns its temporary compilation files, archive readers, and optional dependency copies.
Returned outcomes remain usable after cleanup and subsequent jobs.
The tracer is not a sandbox. Source parsing and compilation run in the host process, including breakpoint discovery, and guest programs can access their process environment and filesystem. Resource budgets and field-only inspection do not isolate either part of the operation. Run trusted programs directly; hosted student submissions require whole-job isolation as described in the runner contract.
Start with a single trace
Tracer compiles the submitted program, traces it in a
guest JVM, and releases the job's resources before returning a detached
TraceOutcome. This complete example checks the reported
completion state, preserves guest stderr separately, and prints guest stdout followed by the JSON result envelope:
import cs1302.tracer.api.TraceOutcome;
import cs1302.tracer.api.TraceRequest;
import cs1302.tracer.api.Tracer;
/** Demonstrates tracing a Java program through the library API. */
public class TraceExample {
public static void main(String[] args) {
String source = """
/** Prints a greeting from the traced program. */
public class Main {
public static void main(String[] args) {
System.out.println("hello");
} // main
} // Main
""";
TraceOutcome outcome = Tracer.trace(new TraceRequest(source));
if (!"completed".equals(outcome.status()) || !outcome.complete()) {
System.err.println("Trace " + outcome.status() + ": " + outcome.stopReason());
for (String diagnostic : outcome.diagnostics()) {
System.err.println(diagnostic);
} // for
} // if
System.err.print(outcome.stderr());
System.out.print(outcome.stdout());
System.out.println(outcome.json());
} // main
} // TraceExample
The convenience TraceRequest constructor selects Python Tutor output, main-exit capture, finite
instructor budgets, and trusted inspection. Use TraceRequest.builder(source) or the full constructor to supply
stdin, choose a format and capture settings, or configure
TraceLimits and InspectionPolicy.
The overload Tracer.trace(request, true) opts into binary metadata alongside existing literals;
the overload without that argument omits the metadata.
Binary metadata describes captured values, not physical guest storage. It expands
serialized output without changing retained snapshot accounting.
See the encoding definitions and references
for normative specifications, informative explanations, and tracer-defined conventions.
Input is source text, including the documented delimited multi-file syntax;
neighboring source files are not discovered automatically.
Configure binary dependencies
TraceClassPath describes ordered binary directories,
JARs, and explicit glob selections. Its builder does not read files. Each tracing
or discovery operation resolves paths against the process working directory,
expands patterns, and follows available local manifest dependencies:
TraceClassPath dependencies = TraceClassPath.builder()
.addPath(java.nio.file.Path.of("build/classes"))
.addGlob(java.nio.file.Path.of("lib"), "**/*.jar")
.copy(true)
.build();
TraceOutcome outcome = Tracer.trace(request, dependencies);
Dependencies are borrowed by default and must remain available and unchanged until the operation finishes. Optional copying captures the available transitive dependency set before compilation, preserving JAR contents and signatures; all owned readers and copies are released afterward. Glob discovery skips symbolic links by default, while directory copying rejects encountered links. The optional following setting permits outside targets and rejects broken links or cycles. Copying is not an atomic filesystem snapshot or an isolation boundary.
The same selected binary dependencies support compilation, type analysis, and
guest execution. Generic declarations in those binaries support reconstructed
heap type labels through superclass and interface hierarchies, including inherited
fields resolved against their declaring class. Library source and local-variable
debug tables are not required for those declarations. These labels describe
available type evidence; they do not make Java's erased type arguments available
through runtime reflection. Library source-line breakpoints are not added. Source discovery
and source-byte/file limits remain separate; those limits do not bound binary
dependencies. Guest compilation disables annotation processing, so required
generated declarations must be supplied as sources. See TraceClassPath
for selection, duplicate, manifest, and copying rules.
A hidden lambda object without a reconstructed source body can use an observed,
verified functional-interface view for its heap label, such as
Comparator<Person>λ. The marker identifies a lambda implementation while
preserving its object identity; it is not a declared class name. Unknown or
incompatible evidence retains a conservative label, and ordinary concrete classes
and reconstructed lambda bodies retain their existing representations.
Bundle source files
SourceBundle captures an ordered set of named
source texts and emits the existing delimiter format. Explicit paths support empty
or invalid Java text; inferred names require exactly one public top-level type,
or a sole top-level type when none is public. Pass the resulting text to the existing
request builder:
SourceBundle bundle = SourceBundle.builder()
.addSource("demo/Helper.java", """
package demo;
class Helper {
static int answer() { return 42; }
}
""")
.addInferredSource("""
package demo;
public class Main {
public static void main(String[] args) {
System.out.println(Helper.answer());
}
}
""")
.build();
TraceOutcome result = Tracer.trace(TraceRequest.builder(bundle.source()).build());
The named types above are in cs1302.tracer.api. File additions strictly decode UTF-8 and
close their handles before returning; later file changes do not affect captured text. Built bundles are immutable,
and toBuilder() copies captured entries without rereading files. Construction validates logical paths
and delimiter framing, rather than compilation, dependency completeness, or entry-point availability.
Bulk additions capture root-relative glob matches in lexical path order and update the builder only after
the whole group validates. Discovered symbolic links are skipped by default; optional following can reach
outside the selected root. Capturing files is not an atomic filesystem snapshot. See
SourceBundle.Builder for file naming, glob syntax, link handling, and validation;
SourceBundle defines delimiter framing and text preservation.
source() returns the framed text. Each openStream() returns a
fresh independent UTF-8 input stream. writeUtf8(OutputStream) writes the
same representation without flushing or closing the caller's stream.
Configure capture and batch processing
Requests and limits have reusable builders and toBuilder()
copy methods. TraceLimits.builder() starts with instructor defaults;
TraceLimits.unlimited().toBuilder() starts with unlimited budgets.
Builders preserve requested settings; tracing owns policy resolution and execution validation.
TraceLimits limits = TraceLimits.builder().timeoutMillis(5_000).snapshots(500).build();
TraceRequest request = TraceRequest.builder(source).limits(limits).build();
TraceRequest modern = request.toBuilder().format(TraceFormat.MODERN).build();
The named types above are in cs1302.tracer.api. All builders are mutable
and not thread-safe. Immediate collections are detached; arbitrary nested values
are not recursively copied, and existing constructors retain their ownership rules.
BatchTracer.builder() requires explicit positive workers,
maxJobsPerWorker, and maxInFlight settings. Completion-order output
defaults to false. Missing settings fail at build time; numeric ranges are validated
before resource allocation. Each successful build owns a fresh processor, which
must be closed independently. There is no copy builder for a live processor.
Read the outcome
Compilation failures, observed guest failures, and resource stops are represented in the outcome.
Inspect the reported status(), complete(), stopReason(),
diagnostics(), and guest stderr(). In single-stack Java and batch jobs, an uncaught exception
thrown inside a JDK or binary-dependency method can currently leave status: completed and
complete: true, with the exception stack trace in stderr. Status alone is therefore insufficient to
establish that guest execution succeeded; stderr can also contain ordinary application messages.
See TraceOutcome for result-component semantics and current limitations.
json() returns
the result envelope; traceJson() returns its trace payload, or the JSON
literal null when no payload is available. The payload follows batch
result-envelope conventions, rather than ordinary CLI selected-breakpoint map
presentation. The
result-envelope reference
defines the wire schema, counters, phases, and stop codes; the
output reference
describes the two payload formats. Outcomes remain usable after cleanup and after subsequent jobs.
TraceOutcome.builder() supports explicitly supplied outcomes for adapters
and fixtures. It defaults collections to empty, completion to false, and strings to
null. toBuilder() preserves metadata and JSON verbatim. Neither builder
parses, generates, nor synchronizes JSON: changing metadata requires corresponding
JSON if agreement is needed. Production tracing performs coherent rendering before
returning. writeJson requires a supplied envelope string.
Guest lifetime and reuse
Tracer.trace owns a worker for one call and closes it before returning.
Single-stack Java calls and single-stack batch jobs execute through the reusable guest harness;
multithread jobs use dedicated guests. A BatchTracer can reuse a single-stack guest across jobs
until recycling, so a fresh application class loader does not imply a fresh JVM.
The reusable harness restores system properties, default locales, the default time zone,
standard streams, and the default uncaught-exception handler between jobs. Other JDK-global state,
such as the default java.net.CookieHandler or logger configuration, can persist.
When the entry method returns, the harness interrupts lingering job threads rather than waiting indefinitely
for ordinary non-daemon thread lifetime. An explicit System.exit, including status zero, ends the
reusable guest and is reported as guest_exit unless an earlier stop or failure takes precedence.
Use maxJobsPerWorker=1 when batch jobs
need fresh guest JVMs; this remains separate from host/OS isolation.
See BatchTracer for worker ownership and stream-processing rules.
Runtime and compatibility
The regular JAR is intended for library integration; the dependency-bundled JAR is
the executable CLI distribution. Both use the automatic module name
cs1302.tracer. Features of submitted programs depend on the active JDK and parser support.
The current Maven coordinates are io.github.cs1302uga:cs1302-tracer.
Historical releases through 4.3.0 use group ID cs1302uga; updating the Maven
group ID does not change Java package names. Stable releases adopting Central publication
include sources and API Javadoc artifacts; development snapshots require local installation.
CLI calls, including help and version, require matching stable Java/compiler releases of 21 or later.
A nonempty JAVA_HOME selects both tools; otherwise both must be executable on PATH.
The selected JDK must match the running JVM. Failed checks report stderr diagnostics and exit status 1.
The executable JAR has a Java-8-compatible bootstrap solely for unsupported-runtime diagnostics;
the tracer and supported API remain compiled for Java 21. Calls through Tracer and
BatchTracer do not run the CLI environment preflight.
API Guardian is a transitive compile dependency. Maven resolves it automatically; manual compilation against the regular JAR also requires the API Guardian JAR to avoid missing annotation warnings. It supplies stability metadata, while supported method and field types remain project-owned or ordinary Java types.
The supported Java interface is cs1302.tracer.api, together with the
App launcher. Packages under cs1302.tracer.internal
are implementation details outside that contract. Java API compatibility and
serialized JSON compatibility are separate concerns. Guest execution is not a
sandbox: resource budgets do not replace process or host isolation.
Supported types declare STABLE, promising compatibility throughout the
4.x series. Existing types date that status to 4.0.0; SourceBundle,
TraceClassPath, their nested types, and new builders date it to 4.1.0. Public implementation types declare
INTERNAL. A type's status applies to its public members unless explicitly
overridden. The since value dates the stability status, rather than the
original introduction of the code.
Further reading
External guide links on this page lead to the current development documentation: