cs1302-tracer 4.2.1 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

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 prints the guest's output, 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));
        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 original trace method defaults it to false. The request record shape is unchanged. 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. Existing trace overloads and the TraceRequest record shape remain available.

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

Since 4.1.0, 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. addFile(logicalPath, path) and addInferredFile(path) strictly decode UTF-8 files when added and close their file handles. Later changes to those files do not affect captured text. Built bundles are immutable; toBuilder() copies their ordered entries without rereading files. At least one entry is required.

addFiles(root, glob) selects regular files with root-relative logical paths; addInferredFiles(root, glob) infers logical paths from each selected file's Java declarations. Both append matches in case-sensitive lexical order of the encountered relative paths. Portable patterns use / separators and support component wildcards, character classes, non-nested brace alternatives, and whole-component **. For example, demo/**/*.java matches both demo/Main.java and deeper files. No implicit extension or hidden-file filter is applied, but selected files must pass the chosen naming and content validation. Zero matches is an error.

The two-argument bulk methods skip discovered symbolic links. Their overloads with followLinks=true follow links, including targets outside the root, and abort on encountered broken links or directory cycles. The caller-selected root is resolved once and may itself be a symbolic link in either mode. Aliases retain their encountered relative paths rather than being deduplicated by physical identity. Each call captures all selected UTF-8 text and validates all entries before changing the builder; failures preserve previous entries. This does not guarantee a simultaneous snapshot of the filesystem.

Every entry receives a delimiter. Source text, including line endings and BOMs, is preserved except for an LF inserted when needed before a following delimiter; the final source is unchanged. Duplicate logical paths and delimiter collisions are rejected, including collisions inside text blocks or comments. Bundling does not compile Java, establish dependency completeness, or change entry-point selection.

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.

Choose an entry point

Since 4.1.0, 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 still owns policy resolution and execution validation. Existing constructors remain available.

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.

  • Tracer.trace: execute one self-contained tracing request.
  • Tracer.discoverBreakpoints: compile source and discover executable lines without running guest code. Inspect the returned locations and preparation diagnostics.
  • BatchTracer: process the NDJSON batch protocol with reusable workers. Use try-with-resources to release workers; call processStream sequentially. Input and output streams remain caller-owned.

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

Expected compilation and execution failures are represented in the outcome. Inspect status(), complete(), stopReason(), and diagnostics() before treating a trace as complete. 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. 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.

Runtime and compatibility

Run with a full JDK 21 or later and the tracer's runtime dependencies. CI exercises Java 21 and 25; the local development JDK is selected by .java-version. 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.

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

The following links lead to the current development documentation:

Modules
Module
Description