Merge pull request #830 from internetarchive/soft404-probe-any-hop

Soft404Detector: probe more servers and catch soft 404s that appear mid-crawl
This commit is contained in:
Alex Osborne authored and GitHub committed 2026-11-26 15:59:55 +09:00
commit f08fdb2cee
4 files changed
+298 -82

No files matched your search

@@ -38,6 +38,7 @@ import org.archive.bdb.AutoKryo;
import org.archive.modules.CrawlURI;
import org.archive.modules.credential.Credential;
import org.archive.modules.fetcher.FetchStats;
import org.archive.modules.processor.Soft404Detector;
import org.archive.net.UURI;
import org.archive.net.UURIFactory;
import org.archive.util.IdentityCacheable;
@@ -81,10 +82,7 @@ public class CrawlServer implements Serializable, FetchStats.HasFetchStats, Iden
protected int http3Port;
protected long http3Expiry;
/** Soft 404 detection state, maintained by Soft404Detector. */
protected boolean soft404ProbeScheduled;
/** Non-null only if the probe found a soft 404. */
protected Long soft404Fingerprint;
protected Soft404Detector.State soft404State;
/**
* Creates a new CrawlServer object.
@@ -259,36 +257,11 @@ public class CrawlServer implements Serializable, FetchStats.HasFetchStats, Iden
}
/**
* Marks the soft 404 probe as scheduled, unless it already was.
* @return true if the caller should schedule a probe
* Soft 404 detection state, maintained by Soft404Detector. Created when first requested.
*/
public synchronized boolean startSoft404Probe() {
if (soft404ProbeScheduled) return false;
soft404ProbeScheduled = true;
return true;
}
public synchronized boolean isSoft404ProbeScheduled() {
return soft404ProbeScheduled;
}
/**
* @return the fingerprint of the page returned with a success status for a nonexistent URL,
* or null if there is none
*/
public synchronized Long getSoft404Fingerprint() {
return soft404Fingerprint;
}
/**
* Records the fingerprint of the page returned with a success status for a nonexistent URL,
* unless one was already recorded.
* @return true if the fingerprint was recorded
*/
public synchronized boolean setSoft404FingerprintIfAbsent(long fingerprint) {
if (soft404Fingerprint != null) return false;
soft404Fingerprint = fingerprint;
return true;
public synchronized Soft404Detector.State getSoft404State() {
if (soft404State == null) soft404State = new Soft404Detector.State();
return soft404State;
}
public synchronized void clearAltSvc() {
@@ -400,6 +373,7 @@ public class CrawlServer implements Serializable, FetchStats.HasFetchStats, Iden
kryo.register(CrawlServer.class);
kryo.autoregister(FetchStats.class);
kryo.autoregister(Robotstxt.class);
kryo.autoregister(Soft404Detector.State.class);
}
//
@@ -21,8 +21,10 @@ package org.archive.modules.processor;
import static java.nio.charset.StandardCharsets.UTF_8;
import java.io.IOException;
import java.io.Serializable;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.List;
@@ -62,6 +64,11 @@ import com.google.common.hash.Hashing;
* typically change from request to request, such as nonces, timestamps and the page's own URL, are
* ignored when comparing content.
* <p>
* What a server returns for missing URLs can change during a crawl, for example once it has set a
* session cookie. So if a page has the same content as another recent page from the server, the
* server is probed again, up to {@code maxProbes} probes in all (2 by default). Pages matching any
* probe fingerprint are treated as soft 404s.
* <p>
* Soft 404s are annotated "soft404" in the crawl log, and the probe "soft404:probe". If
* {@code skipExtraction} is enabled (the default) the rest of the fetch chain is skipped for
* them, so neither the link extractors nor the browser processor see them, which stops the series
@@ -71,7 +78,10 @@ import com.google.common.hash.Hashing;
* <p>
* Things to be aware of:
* <ul>
* <li>Each server gets one extra request, the probe, which is archived like any other.</li>
* <li>Each server that returns an HTML page gets one extra request, the probe, or up to
* {@code maxProbes} with re-probes. Probes are archived like any other request. This includes
* servers reached only by embeds or redirects, as soft 404s can produce endless URLs through those
* too.</li>
* <li>Pages fetched before a server's probe completes aren't checked.</li>
* <li>Seeds and the root URL ("/") are never treated as soft 404s, since many sites serve their
* home page for missing URLs.</li>
@@ -119,6 +129,19 @@ public class Soft404Detector extends Processor {
kp.put("skipExtraction", skipExtraction);
}
{
setMaxProbes(2);
}
public int getMaxProbes() {
return (Integer) kp.get("maxProbes");
}
/**
* Maximum number of probes per server.
*/
public void setMaxProbes(int maxProbes) {
kp.put("maxProbes", maxProbes);
}
protected ServerCache serverCache;
public ServerCache getServerCache() {
@@ -151,40 +174,63 @@ public class Soft404Detector extends Processor {
protected ProcessResult innerProcessResult(CrawlURI curi) throws InterruptedException {
CrawlServer server = serverCache.getServerFor(curi.getUURI());
if (server == null) return ProcessResult.PROCEED;
State state = server.getSoft404State();
server.makeDirty(); // as the state may change below
if (isProbe(curi)) {
recordProbeResult(curi, server);
recordProbeResult(curi, state);
// A redirected probe must continue so its Location gets extracted. Otherwise there's
// nothing worth extracting from a made-up URL.
int status = curi.getFetchStatus();
return status >= 300 && status < 400 ? ProcessResult.PROCEED : ProcessResult.FINISH;
}
Long fingerprint = server.getSoft404Fingerprint();
if (fingerprint == null) {
scheduleProbe(curi, server);
if (!state.isProbeScheduled()) {
scheduleProbe(curi, state, false);
return ProcessResult.PROCEED;
}
if (isExempt(curi) || curi.getFetchStatus() != 200 || fingerprint(curi) != fingerprint) {
if (isExempt(curi) || curi.getFetchStatus() != 200) return ProcessResult.PROCEED;
// nothing to match against and no probe to start, so no need to hash the content
if (!state.hasFingerprints() && !state.canStartProbe(getMaxProbes())) {
return ProcessResult.PROCEED;
}
curi.getAnnotations().add(ANNOTATION);
soft404sDetected.incrementAndGet();
return getSkipExtraction() ? ProcessResult.FINISH : ProcessResult.PROCEED;
String content = readContent(curi);
long fingerprint = fingerprint(content, echoesOf(curi.getUURI()));
if (matchesProbe(content, fingerprint, state)) {
curi.getAnnotations().add(ANNOTATION);
soft404sDetected.incrementAndGet();
return getSkipExtraction() ? ProcessResult.FINISH : ProcessResult.PROCEED;
}
// If the same page is served for several URLs, probe again in case it's a soft 404 that
// the earlier probes missed, e.g. because they ran before a session cookie was set.
if (state.canStartProbe(getMaxProbes()) && state.addRecentPage(fingerprint)) {
scheduleProbe(curi, state, true);
}
return ProcessResult.PROCEED;
}
protected void scheduleProbe(CrawlURI curi, CrawlServer server) {
/**
* Whether the content matches what a probe got, either with its echoes of its own URL removed
* (giving the given fingerprint) or as is. The latter catches a page reached by a relative
* link on a copy of itself, where the "echo" is part of the page and so also in the probe's
* content.
*/
private static boolean matchesProbe(String content, long fingerprint, State state) {
if (!state.hasFingerprints()) return false;
return state.isFingerprint(fingerprint)
|| state.isFingerprint(fingerprint(content, List.of()));
}
protected void scheduleProbe(CrawlURI curi, State state, boolean reprobe) {
int status = curi.getFetchStatus();
if (status < 200 || status >= 400) return;
// Only probe servers reached as seeds or by following links, not e.g. CDNs or other
// sites that a crawled site redirects to.
String hop = curi.getLastHop();
if (!hop.isEmpty() && !hop.equals(Hop.NAVLINK.getHopString())) return;
if (!server.startSoft404Probe()) return;
server.makeDirty();
if (!state.startProbe(getMaxProbes())) return;
try {
UURI probeUri = UURIFactory.getInstance(curi.getUURI(), probePath);
CrawlURI probe = curi.createCrawlURI(probeUri, LinkContext.INFERRED_MISC, Hop.INFERRED);
probe.setSchedulingDirective(SchedulingConstants.HIGH);
// re-probes reuse the probe URL, so must bypass the already-seen check
probe.setForceFetch(reprobe);
curi.getOutLinks().add(probe);
probesScheduled.incrementAndGet();
} catch (URIException e) {
@@ -192,16 +238,14 @@ public class Soft404Detector extends Processor {
}
}
protected void recordProbeResult(CrawlURI curi, CrawlServer server) {
protected void recordProbeResult(CrawlURI curi, State state) {
curi.getAnnotations().add(PROBE_ANNOTATION);
// a probe redirected from another server counts as this server's probe
if (server.startSoft404Probe()) server.makeDirty();
state.finishProbe();
if (curi.getFetchStatus() != 200 || curi.getContentLength() <= 0 || !isHtml(curi)) return;
if (!server.setSoft404FingerprintIfAbsent(fingerprint(curi))) return;
server.makeDirty();
if (!state.addFingerprint(fingerprint(curi))) return;
serversWithSoft404s.incrementAndGet();
if (logger.isLoggable(Level.FINE)) {
logger.fine("Soft 404s detected on " + server);
logger.fine("Soft 404s detected by " + curi);
}
}
@@ -242,8 +286,11 @@ public class Soft404Detector extends Processor {
}
static long fingerprint(CrawlURI curi) {
String normalized = normalize(readContent(curi), echoesOf(curi.getUURI()));
return Hashing.murmur3_128().hashString(normalized, UTF_8).asLong();
return fingerprint(readContent(curi), echoesOf(curi.getUURI()));
}
private static long fingerprint(String content, List<String> echoes) {
return Hashing.murmur3_128().hashString(normalize(content, echoes), UTF_8).asLong();
}
/**
@@ -372,4 +419,96 @@ public class Soft404Detector extends Processor {
" Servers with soft 404s: " + serversWithSoft404s.get() + "\n" +
" Soft 404s detected: " + soft404sDetected.get() + "\n";
}
/**
* Soft 404 detection state of one server, kept in its {@link CrawlServer}.
*/
public static class State implements Serializable {
private static final long serialVersionUID = 1L;
/** Number of recent page fingerprints kept to spot repeated pages. */
static final int RECENT_PAGES = 8;
private int probeCount;
private boolean probePending;
/** Fingerprints of soft 404 pages that probes found, or null if none did. */
private long[] fingerprints;
/** Fingerprints of recent pages, oldest first, or null if none are being kept. */
private long[] recentPages;
/**
* Marks a probe as scheduled, unless one is pending or maxProbes have already been
* scheduled.
* @return true if the caller should schedule a probe
*/
public synchronized boolean startProbe(int maxProbes) {
if (!canStartProbe(maxProbes)) return false;
probeCount++;
probePending = true;
recentPages = null;
return true;
}
public synchronized boolean canStartProbe(int maxProbes) {
return !probePending && probeCount < maxProbes;
}
/**
* Marks the pending probe as done, or records a probe of this server that was scheduled
* elsewhere, e.g. one redirected from another server.
*/
public synchronized void finishProbe() {
probeCount = Math.max(probeCount, 1);
probePending = false;
}
public synchronized boolean isProbeScheduled() {
return probeCount > 0;
}
public synchronized boolean hasFingerprints() {
return fingerprints != null;
}
/**
* Whether a probe got a page with this fingerprint with a success status for a
* nonexistent URL.
*/
public synchronized boolean isFingerprint(long fingerprint) {
return fingerprints != null && contains(fingerprints, fingerprint);
}
/**
* Records the fingerprint of a page a probe got with a success status for a nonexistent
* URL.
* @return true if it's the first one recorded
*/
public synchronized boolean addFingerprint(long fingerprint) {
if (isFingerprint(fingerprint)) return false;
long[] old = fingerprints == null ? new long[0] : fingerprints;
fingerprints = Arrays.copyOf(old, old.length + 1);
fingerprints[old.length] = fingerprint;
return old.length == 0;
}
/**
* Records the fingerprint of a page, keeping only the most recent RECENT_PAGES.
* @return true if one of the kept pages already had this fingerprint
*/
public synchronized boolean addRecentPage(long fingerprint) {
long[] pages = recentPages == null ? new long[0] : recentPages;
if (contains(pages, fingerprint)) return true;
int keep = Math.min(pages.length, RECENT_PAGES - 1);
recentPages = Arrays.copyOfRange(pages, pages.length - keep, pages.length + 1);
recentPages[keep] = fingerprint;
return false;
}
private static boolean contains(long[] values, long value) {
for (long v : values) {
if (v == value) return true;
}
return false;
}
}
}
@@ -40,18 +40,21 @@ public class CrawlServerTest {
}
@Test
public void testKryoRoundTripKeepsSoft404Fingerprint() {
public void testKryoRoundTripKeepsSoft404State() {
CrawlServer server = new CrawlServer("example.com:443");
server.startSoft404Probe();
server.setSoft404FingerprintIfAbsent(42);
server.getSoft404State().startProbe(3);
server.getSoft404State().finishProbe();
server.getSoft404State().addRecentPage(7);
server.getSoft404State().addFingerprint(42);
KryoBinding<CrawlServer> binding = new KryoBinding<>(CrawlServer.class);
DatabaseEntry entry = new DatabaseEntry();
binding.objectToEntry(server, entry);
CrawlServer restored = binding.entryToObject(entry);
assertTrue(restored.isSoft404ProbeScheduled());
assertEquals(42L, restored.getSoft404Fingerprint());
assertTrue(restored.getSoft404State().isProbeScheduled());
assertTrue(restored.getSoft404State().isFingerprint(42));
assertTrue(restored.getSoft404State().addRecentPage(7));
}
@Test
@@ -67,8 +67,8 @@ class Soft404DetectorTest {
assertEquals("https://example.com" + detector.getProbePath(), probe.getURI());
assertEquals("I", probe.getPathFromSeed());
assertEquals(SchedulingConstants.HIGH, probe.getSchedulingDirective());
assertTrue(server().isSoft404ProbeScheduled());
assertNull(server().getSoft404Fingerprint());
assertTrue(state().isProbeScheduled());
assertFalse(state().hasFingerprints());
CrawlURI page = curi("https://example.com/page", 200);
detector.process(page);
@@ -82,7 +82,7 @@ class Soft404DetectorTest {
detector.process(robots);
assertTrue(robots.getOutLinks().isEmpty());
assertFalse(server().isSoft404ProbeScheduled());
assertFalse(state().isProbeScheduled());
}
@Test
@@ -92,7 +92,7 @@ class Soft404DetectorTest {
recordResponse(probe, "<h1>Not Found</h1>");
detector.process(probe);
assertNull(server().getSoft404Fingerprint());
assertFalse(state().hasFingerprints());
assertTrue(probe.getAnnotations().contains(Soft404Detector.PROBE_ANNOTATION));
CrawlURI page = curi("https://example.com/a/b", 200);
@@ -109,7 +109,7 @@ class Soft404DetectorTest {
recordResponse(probe, spaShell(probe.getUURI().getPath(),
"v1.eyJwcm9qZWN0X2lkIjoibG92cF8xcDNh.ULHj8Snk4GlGG5Teb57oUauBA3QoDzudjWFrtVjiBUg"));
assertEquals(ProcessResult.FINISH, detector.process(probe));
assertNotNull(server().getSoft404Fingerprint());
assertTrue(state().hasFingerprints());
CrawlURI page = curi("https://example.com/_ignition/horizon/api/jobs"
+ "/_ignition/salt-edge/get-consent", 200);
@@ -156,19 +156,24 @@ class Soft404DetectorTest {
}
@Test
void laterProbeDoesNotReplaceFingerprint() throws Exception {
void laterProbeAddsFingerprintWithoutCountingServerAgain() throws Exception {
// e.g. the http:// server's probe redirected to this server, which also had its own probe
CrawlURI probe = probe();
recordResponse(probe, "<html><title>Not here</title></html>");
detector.process(probe);
Long fingerprint = server().getSoft404Fingerprint();
CrawlURI redirected = curi("https://example.com" + detector.getProbePath(), 200);
recordResponse(redirected, "<html><title>Something else</title></html>");
detector.process(redirected);
assertEquals(fingerprint, server().getSoft404Fingerprint());
assertEquals(1, detector.getServersWithSoft404s());
for (String body : List.of("<html><title>Not here</title></html>",
"<html><title>Something else</title></html>")) {
CrawlURI page = curi("https://example.com/a/" + body.length(), 200);
recordResponse(page, body);
detector.process(page);
assertTrue(page.getAnnotations().contains(Soft404Detector.ANNOTATION), body);
}
}
@Test
@@ -178,7 +183,7 @@ class Soft404DetectorTest {
recordResponse(probe, "{\"error\":\"not found\",\"code\":404}");
assertEquals(ProcessResult.FINISH, detector.process(probe));
assertNull(server().getSoft404Fingerprint());
assertFalse(state().hasFingerprints());
assertEquals(0, detector.getServersWithSoft404s());
}
@@ -189,12 +194,12 @@ class Soft404DetectorTest {
assertEquals(ProcessResult.PROCEED, detector.process(robots));
assertTrue(robots.getOutLinks().isEmpty());
assertFalse(server().isSoft404ProbeScheduled());
assertFalse(state().isProbeScheduled());
}
@ParameterizedTest
@ValueSource(strings = {"LE", "LR", "LX"})
void onlyProbesFromSeedsAndNavlinks(String pathFromSeed) throws Exception {
@ValueSource(strings = {"LL", "LE", "LR", "LX"})
void probesFromAnyHop(String pathFromSeed) throws Exception {
CrawlURI page = new CrawlURI(UURIFactory.getInstance("https://example.com/page"),
pathFromSeed, UURIFactory.getInstance("https://other.example/"),
LinkContext.NAVLINK_MISC);
@@ -203,8 +208,8 @@ class Soft404DetectorTest {
page.setContentType("text/html");
detector.process(page);
assertTrue(page.getOutLinks().isEmpty());
assertFalse(server().isSoft404ProbeScheduled());
assertEquals(1, page.getOutLinks().size());
assertTrue(state().isProbeScheduled());
}
@Test
@@ -214,8 +219,79 @@ class Soft404DetectorTest {
detector.process(redirected);
CrawlServer www = serverCache.getServerFor("www.example.com:443");
assertNotNull(www.getSoft404Fingerprint());
assertTrue(www.isSoft404ProbeScheduled());
assertTrue(www.getSoft404State().hasFingerprints());
assertTrue(www.getSoft404State().isProbeScheduled());
}
@Test
void reprobesWhenPagesRepeatAfterSoft404Found() throws Exception {
// e.g. a login page for missing URLs until a session cookie is set, then an app shell
String login = "<html><title>Please log in</title></html>";
CrawlURI probe = probe();
recordResponse(probe, login);
detector.process(probe);
String shell = "<html><body><div id=\"root\"></div></body></html>";
CrawlURI first = curi("https://example.com/favicon.ico", 200);
recordResponse(first, shell);
detector.process(first);
CrawlURI second = curi("https://example.com/a/b/fav.ico", 200);
recordResponse(second, shell);
detector.process(second);
assertFalse(second.getAnnotations().contains(Soft404Detector.ANNOTATION));
assertEquals(1, second.getOutLinks().size());
CrawlURI reprobe = second.getOutLinks().iterator().next();
assertEquals("https://example.com" + detector.getProbePath(), reprobe.getURI());
assertTrue(reprobe.forceFetch());
respond(reprobe, 200, shell);
for (String body : List.of(shell, login)) {
CrawlURI page = curi("https://example.com/a/b/c/" + body.length(), 200);
recordResponse(page, body);
detector.process(page);
assertTrue(page.getAnnotations().contains(Soft404Detector.ANNOTATION), body);
}
assertEquals(1, detector.getServersWithSoft404s());
}
@Test
void doesNotReprobeWhenMaxProbesIsOne() throws Exception {
detector.setMaxProbes(1);
respond(probe(), 404, "<h1>Not Found</h1>");
for (String path : List.of("/a/1", "/a/2", "/a/3")) {
CrawlURI page = curi("https://example.com" + path, 200);
recordResponse(page, "<html><title>Same</title></html>");
detector.process(page);
assertTrue(page.getOutLinks().isEmpty(), path);
}
}
private static final int MAX_PROBES = 3;
@Test
void stateLimitsProbes() {
Soft404Detector.State state = new Soft404Detector.State();
for (int i = 0; i < MAX_PROBES; i++) {
assertTrue(state.canStartProbe(MAX_PROBES));
assertTrue(state.startProbe(MAX_PROBES));
assertFalse(state.canStartProbe(MAX_PROBES), "one is pending");
assertFalse(state.startProbe(MAX_PROBES), "one is pending");
state.finishProbe();
}
assertFalse(state.canStartProbe(MAX_PROBES), "limit reached");
assertFalse(state.startProbe(MAX_PROBES), "limit reached");
}
@Test
void stateKeepsOnlyRecentPages() {
Soft404Detector.State state = new Soft404Detector.State();
for (long page = 1; page <= Soft404Detector.State.RECENT_PAGES + 1; page++) {
assertFalse(state.addRecentPage(page));
}
assertFalse(state.addRecentPage(1));
assertTrue(state.addRecentPage(Soft404Detector.State.RECENT_PAGES + 1));
}
@Test
@@ -257,6 +333,22 @@ class Soft404DetectorTest {
assertTrue(page.getAnnotations().contains(Soft404Detector.ANNOTATION));
}
@Test
void detectsSoft404ReachedByItsOwnRelativeLink() throws Exception {
// an app shell served for every path, fetched at one of its own relative links
String shell = "<html><head><link rel=\"stylesheet\" href=\"assets/css/styles.css\">"
+ "</head><body><div id=\"root\"></div></body></html>";
CrawlURI probe = probe();
recordResponse(probe, shell);
detector.process(probe);
CrawlURI page = curi("https://example.com/assets/css/styles.css", 200);
recordResponse(page, shell);
detector.process(page);
assertTrue(page.getAnnotations().contains(Soft404Detector.ANNOTATION));
}
@Test
void detectsSoft404EchoingPercentEncodedUrl() throws Exception {
// e.g. www.meetup.com: <a href="/login/?returnUri=https%3A%2F%2Fwww.meetup.com%2F...">
@@ -280,13 +372,13 @@ class Soft404DetectorTest {
"https://example.com/kr-ko" + probe.getUURI().getPath() + "/");
// must proceed so ExtractorHTTP follows the redirect
assertEquals(ProcessResult.PROCEED, detector.process(probe));
assertNull(server().getSoft404Fingerprint());
assertFalse(state().hasFingerprints());
String body = "<html><title>Home</title><a href=\"premium/\">Premium</a></html>";
CrawlURI target = curi("https://example.com/kr-ko" + probe.getUURI().getPath() + "/", 200);
recordResponse(target, body);
assertEquals(ProcessResult.FINISH, detector.process(target));
assertNotNull(server().getSoft404Fingerprint());
assertTrue(state().hasFingerprints());
assertTrue(target.getAnnotations().contains(Soft404Detector.PROBE_ANNOTATION));
CrawlURI page = curi("https://example.com/uk/icantypeanythinghere/", 200);
@@ -370,8 +462,16 @@ class Soft404DetectorTest {
assertEquals(detector.getProbePath(), restored.getProbePath());
}
private CrawlServer server() {
return serverCache.getServerFor("example.com:443");
private Soft404Detector.State state() {
return serverCache.getServerFor("example.com:443").getSoft404State();
}
private void respond(CrawlURI curi, int status, String body) throws Exception {
curi.setFetchStatus(status);
curi.setFetchType(CrawlURI.FetchType.HTTP_GET);
curi.setContentType("text/html");
recordResponse(curi, body);
detector.process(curi);
}
private CrawlURI probe() throws Exception {