HTMLCSSJAVASCRIPTANGULARINTERVIEW QUESTIONSSQLPYTHONJAVAPHPHOW TOW3.CSSCC++C#BOOTSTRAPREACTNEXTJSMYSQLJQUERYEXCELXMLDJANGONUMPYPANDASNODEJSDSATYPESCRIPTANGULARJSGITPOSTGRESQLMONGODBASPAIRGOKOTLINSWIFTSASSVUEGEN AIAGENTIC AIPROMPT ENGINEERINGDOCKERKUBERNETESSPRINGSPRING BOOTUNIXSCIPYAWSCYBERSECURITYDATA SCIENCEINTRO TO PROGRAMMINGINTRO TO HTML & CSSBASHRUSTTOOLS
AI-Powered Full Stack Tutorial 0/70 lessons ~6 min read Lesson 25“React, Next.js, Node, PostgreSQL, LLMs, RAG, agents, and production AI apps”
Document Ingestion and Parsing Pipelines
The knowledge assistant from lesson 24 abstains when the corpus has no chunk.
Course progress0%
Focus
16 guided sections
Practice signal
Concept-first lesson
Career prep
Foundation builder
AI-Powered Full Stack Development · Lesson 25 · RAG, Search and Knowledge Systems
Lesson Overview
The knowledge assistant from lesson 24 abstains when the corpus has no chunk. That abstention is only as good as the pipeline that admits lesson files. An editor upload named ../../other-org/notes.md was stored under that string as an object key, and a second upload of the same bytes created a second document row because the handler checked "does this filename exist?" before the insert committed. A 2 MB HTML file with a script tag was parsed by concatenating whatever the browser had sent into the body the assistant would later quote. The organization on the row came from a form field.
Ingestion is the index-time door. It accepts bytes the server has already tied to a session, rejects what it will not parse, records a content hash and a parser version, and writes a job row in PostgreSQL. The knowledge assistant never sees the original filename as an identity. It sees a document id, an organization_id taken from the session, and a visibility the server chose. Parsing in this lesson is a markdown line scan you can read in one sitting. PDF and office files sit behind a parser port and return unsupported_media until a reviewed adapter exists. This lesson does not embed and does not chunk. Those are the next two lessons. It makes sure the bytes that reach them belong to one organization and one hash.
A lesson file cap of 1 MiB (1_048_576 bytes) is a product limit for this lab. Raise it with a written reason, not because one file failed.
The hash is SHA-256 of the accepted UTF-8 bytes, via node:crypto. It is an identity for deduplication, not a secret.
Parser version markdown-line-v1 is part of the unique key. A new parser may store a new row. It must not silently overwrite a row another version parsed.
Tests use a fake Queryable. They do not need a running PostgreSQL. The SQL text is still the contract an integration test will execute.
Learning Objectives
By the end of this lesson you will be able to:
Separate index-time ingestion from query-time answering, and name which path may call a model (neither, in this lesson).
Build the caller's organization, course, and visibility on the server, and ignore the same fields in a form body or a frontmatter block.
Reject oversize payloads, NUL bytes, non-UTF-8 sequences, and media types this parser does not implement.
Compute a SHA-256 hex digest and use it with organization_id and parser_version as an idempotency key.
Strip a leading frontmatter fence without reading it as authorization.
Store the original accepted text so the hash and the row agree.
Insert the document and the job with parameterized SQL, and map unique-violation 23505 to "return the existing row."
Record job status as parsed, failed, or quarantined with a stable error_code.
Keep the storage key as the document uuid. Treat the filename as a display hint after path separators are removed.
Explain why an HTML or PDF adapter is a separate reviewed module, and why this lesson fails closed without one.
Test quarantine, idempotent replay, and a cross-organization hash collision that must not return the other row.
Hand lesson 26 a document row whose ACL columns are server-owned.
Node.js 20 or newer for node:crypto and TextDecoder. TypeScript strict. No object-storage SDK is required. No model key is required. /learn/genai stays on the query path, which this lesson does not take.
Detailed Core Concepts
Why the assistant inherits the ingest bug
Lesson 24 can filter a chunk only if the chunk's organizationId is the organization that owned the bytes. If ingest writes organization B's file under organization A because a form field said so, the filter faithfully returns a leak. Ingest is where identity is assigned. Query time is too late to discover that the filename contained ../.
The pipeline also exists because editors retry. A double-click and a timeout retry will both send the same bytes. Without a unique key, the corpus holds two copies, the chunker embeds both, and the ranker spends its limit on duplicates while a newer lesson version sits at position five. Idempotency here is a unique index plus a handler that treats 23505 as success and re-reads the row under the same organization.
What "parsing" means for a lesson file
Parsing turns bytes into a structure the next stage can chunk: a title, a body, and the assurance that the body is text. It does not mean "run the file." Markdown is text. A line that starts with # is a heading because we say so in markdown-line-v1. A line that looks like HTML is still text. It is stored as text and later rendered only through the lesson player's existing escape path. This pipeline does not evaluate it, does not fetch its links, and does not pass it to a model "to clean it up." A model cleanup would be a second writer of canonical lesson text, and the hash would no longer match the editor's file.
Frontmatter between an opening --- and a closing --- is stripped only when a later stage needs the body. The stored body remains the original accepted text so content_sha256 matches what the editor hashed locally. The strip function does not interpret keys. A file that contains visibility: published inside the fence does not publish itself. Visibility is a column set by the route.
Media types and the parser port
typescript
exportinterfaceDocumentParser{
readonly id:string;
supports(mediaType:string):boolean;
parse(text:string):{ title:string};
}
markdown-line-v1 supports text/markdown and text/plain. Anything else, including application/pdf and text/html, returns unsupported_media and a job in quarantined. That is a product decision. PDF text extraction needs a library whose API you verify on the day you add it, and it needs a decision about pages, images, and scanned documents. Shipping a guessed wrapper that returns an empty string would ingest a document the assistant then treats as silence, or worse, as garbage tokens. Fail closed, and write the adapter when you have read that library's current docs. The port is yours. The library is not invented in this lesson.
Job states
Status
Meaning
Next
received
Row inserted, parse not finished
Move to parsing in the same transaction as the insert when the file is small enough to parse inline
parsing
Worker owns the attempt
parsed or failed or quarantined
parsed
Body stored, ready for chunking
Lesson 26
failed
Unexpected error, safe to retry the same hash
A new attempt row, same document
quarantined
The bytes are rejected by policy
Do not chunk. An editor replaces the file
This lab parses inline because a 1 MiB markdown file is a short CPU burst. The job row still exists so the states, the error codes, and the idempotency story match the worker you will want when PDF arrives. Do not mark parsed if the title extractor threw. Do not mark parsed and also leave the body empty.
Hash, version, organization
The unique index is (organization_id, content_sha256, parser_version).
The same bytes in the same organization with the same parser return the existing document.
The same bytes in another organization are a different row. A global unique hash would let organization A learn that organization B had already uploaded a file, which is a side channel, and it would block a legitimate shared syllabus. Scope the hash to the organization.
A new parser_version may insert a new row for the same bytes. Chunking must record which document id it used. Leaving both rows active for retrieval is a lesson 26 decision; ingest only refuses to collapse them.
Filename is not a key
Object storage, when you add it, uses the document uuid. The original filename is stored only after basename logic: drop anything up to the last / or \, reject names that are empty after that, and cap the length. The rejected ../../other-org/notes.md becomes a display string notes.md or a quarantine if you would rather reject path-like names outright. This lesson quarantines a name that contains /, \, or .. so the attempt is visible in error_code = 'path_like_name'. The bytes are not written to a path built from the client string.
Architecture and Request Flow
flowchart TB
subgraph browser [Browser]
Editor[Editor upload]
end
subgraph api [TechLearningPro API]
Auth[Session organization and role]
Gate[Size UTF-8 and media gate]
Parse[markdown-line-v1]
end
subgraph data [PostgreSQL]
Docs[(corpus_documents)]
Jobs[(ingestion_jobs)]
end
Editor -->|bytes and course id| Auth
Auth --> Gate
Gate -->|quarantine| Jobs
Gate --> Parse
Parse --> Docs
Parse --> Jobs
The browser may send a course id the editor is allowed to publish into. The API checks that course belongs to the session organization before insert, with the same INSERT ... SELECT shape as lesson 11's enrollment. The client does not send organization_id that the insert trusts. There is no edge from this diagram to ModelPort. Embedding is a later job that reads parsed rows.
flowchart LR
Bytes[Upload bytes] --> Lim{Within cap and UTF-8}
Lim -->|no| Q[quarantined]
Lim -->|yes| Hash[SHA-256]
Hash --> Ins[Insert document]
Ins -->|23505| Existing[Re-read same organization]
Ins -->|ok| Parsed[status parsed]
Failure points: unauthenticated editor, course outside the organization, oversize, invalid UTF-8, NUL, unsupported media, path-like name, empty body, unique race, database unavailable. Quarantine stores an error code and does not store a body you are unwilling to parse. A database outage returns failed to the client and leaves no half-committed document, because the insert and the job share a transaction.
Step-by-step Implementation
Package path: packages/knowledge-assistant/src/ingest/. Migration file: db/migrations/010_corpus_documents.sql. The application role is app_rw from lesson 11. Migrations run as migrator.
ON ingestion_jobs (organization_id, created_at DESC);
editorial_markdown is the only source_kind this migration allows. A later migration can add upload when a review step exists. Adding it now, with no reviewer, is how an untrusted file becomes a published chunk. The job check constraint forces a quarantine to carry an error_code and forbids a quarantine from pointing at a stored document. A parsed job points at a document and has no error code.
document_id is nullable so a quarantine can be audited without keeping the rejected bytes. If your retention policy requires keeping rejected bytes for a short window, store them in a separate table with a purge job. Do not put them in corpus_documents.body, or the chunker will grow a "where status = parsed" bug and index them anyway.
TextDecoder with fatal: true throws on malformed UTF-8 instead of inserting U+FFFD and hashing a different string than the editor sent. The hash is of the original bytes, computed only after the checks that do not modify them. Quarantine paths do not need a hash of a file you are discarding, and skipping it avoids putting rejected content into a log via the digest lookup. You may still log byte_length, media type, and error_code.
Step 3: Title, without honoring frontmatter policy
const match =/^(#{1,3})\s+(\S.*)$/.exec(line.trim());
if(match)return match[2].trim().slice(0,200);
}
return"Untitled";
}
The stored body is still the original text from acceptLessonBytes. markdownTitle reads a heading. Lesson 26 calls stripLeadingFrontmatter again when it chunks, so a visibility: line never becomes a chunk that outranks the lesson. If the fence is unclosed, the stripper returns the original text and the chunker will see the fence as ordinary lines. That is safer than a YAML parser that might treat the rest of the file as metadata and drop it.
Every value that came from the request is a parameter: organization, course, lesson id, version, visibility, hash, length, title, body. source_kind is a SQL literal the application owns, not a string from the client, so a caller cannot set source_kind to a value the check constraint would reject or, later, to a kind you add for a different trust level. parser_version is the constant PARSER_VERSION.
On 23505 the handler re-reads with all three unique columns. It does not SELECT id FROM corpus_documents WHERE content_sha256 = $1 alone. That query would return another organization's document when hashes collide across tenants, which they may, because the unique index is not global.
recordQuarantine uses the pool outside the document transaction on purpose: the document transaction has not started, and a quarantine must not insert into corpus_documents. If the quarantine insert fails, the route returns 503. It still must not write the body to a log to "make up for" the missing job.
The broad catch maps unexpected errors to db_error and rolls back. It does not include err.message in the API body. PostgreSQL messages can echo constraint details. Log the code server-side. Lesson 11 maps 23503 the same way.
Step 5: How you run it
Apply 010_corpus_documents.sql as migrator on a local database.
Grant app_rwSELECT, INSERT on both tables. Do not grant UPDATE on body to the route role if a later editor flow uses a different statement. This lesson only inserts.
Call ingestLesson with UTF-8 markdown whose media type is text/markdown.
Call it again with the same bytes and expect duplicate: true and the same documentId.
Call it with application/pdf and expect quarantined / unsupported_media and zero corpus_documents rows.
Clean up by deleting the lab organization in a local database, or by using a transaction you roll back in the integration test. Do not point this function at production while you are still printing bodies in a debug log.
Security
The document row is the root of the ACL lesson 24 enforces on chunks. Get the root wrong and every later filter is a precise filter over the wrong tenant.
organizationId comes from the session. The insert's course check is courses.organization_id = $2 with that session value. A course id from another organization inserts nothing and returns course_mismatch.
visibility is an argument the route sets. An instructor publishing through the reviewed action passes published. A save of an unfinished file passes staff. The markdown file is not consulted. stripLeadingFrontmatter exists so a later chunker cannot "helpfully" parse visibility either.
Filenames never become paths. path_like_name quarantines the attempt. The primary key is randomUUID().
Bodies are tenant data. Logs for a successful ingest list documentId, organizationId, byte_length, parser_version, and content_sha256. They do not list body. The hash is not reversible into the lesson text. It is still an identifier, so keep it out of public URLs.
Quarantine does not retain bytes in corpus_documents. A support tool that wants to show the rejected file needs a separate, expiring store and its own ACL.
The route role cannot BYPASSRLS and is not the table owner. Row level security can repeat organization_id = current_setting('app.organization_id')::uuid as defense in depth when you add it. The parameterized predicate in this lesson stays anyway. RLS is not a substitute for a missing WHERE in a job that connects as a privileged role.
No model call means no prompt-injection sink at ingest. The injection problem returns when chunk text is placed in a prompt. Ingest's job is to avoid granting that text a second organization's id.
A duplicate replay must not insert a second parsed job. The handler commits the rollback-free re-read and returns. If you need an audit of retries, write a separate ingest_attempts insert that does not flip status. Two parsed jobs for one document will make a worker chunk twice.
Do not map quarantine to HTTP 200 with an empty document id. Editors will retry the same PDF forever and think it published. Use a 4xx and the stable error_code.
The third test is the ACL point: the original string still contains the key, and the title does not become published. Add an integration test against PostgreSQL that inserts the same hash twice and asserts one row, then inserts the same hash with a second organization_id and asserts two rows. Add a test that a course in organization B returns course_mismatch when the session is organization A. Those two tests are the ones that fail if someone "simplifies" the unique lookup.
Eval for this stage is structural. You are not scoring answer quality. You are scoring whether the corpus grew by the right row. Count quarantined by error_code so a sudden spike in unsupported_media is a product signal (editors need PDF) rather than a silent drop.
Performance and Cost
Parsing 1 MiB of markdown in the request process is a small CPU cost next to a model call, and this path makes no model call. The expensive mistakes are elsewhere.
The cap avoids a multi-hundred-megabyte body landing in text and in a toast of WAL. If editors need larger files, store the blob outside PostgreSQL and keep the row as metadata. Do that as a designed change. Do not raise MAX_BYTES and the check constraint out of band with each other.
Hashing is linear in the file size and cheap at this cap. Do it once. The retry should send the same bytes, not a re-encoded string that changes newlines and misses the unique key.
The unique index makes the duplicate path an index lookup. The race still needs the 23505 handler. An application-level SELECT then INSERT loses to two concurrent requests.
Inline parsing holds a pool client across the hash checks only after connect. acceptLessonBytes runs before connect, so a quarantine does not pin a transaction. Hold the client only for the course check, the insert, and the job.
Cost of this stage is storage: one body per organization per hash per parser version. Re-uploading the same lesson does not multiply rows. Changing the parser version does. Plan a retention rule before you bump PARSER_VERSION weekly.
There is no embedding spend yet. Do not "just embed in the same request" as a shortcut. A failed embed would be tangled with a committed document, and lesson 27's embedder id would be whatever the request handler had in scope. Chunk, then embed, as separate jobs that can retry.
Knowledge Check
1. What problem does this capability solve?
It admits lesson markdown into the corpus under the session's organization, once per hash and parser version, and it refuses bytes this pipeline cannot treat as text. The assistant in lesson 24 can only abstain or answer from rows this door creates.
2. What alternatives exist, and when would you choose each?
Inline parsing fits editorial markdown under a small cap. A background worker fits PDF extraction and anything slower than a request budget. A model-based "cleanup" parser fits nowhere in this pipeline, because the stored body must stay the editor's bytes. A client-side parse fits a preview and does not replace the server check.
3. Which data, identity, and trust boundaries matter?
The session supplies organization_id and the route supplies visibility. The course must belong to that organization. The file supplies bytes and a filename that is not a path. Frontmatter is not an ACL. The hash is unique per organization, not globally. The model provider is not on this path.
4. What can fail, and how should the system respond?
Oversize, NUL, bad UTF-8, unsupported media, path-like names, and empty files quarantine without a document row. A foreign course returns course_mismatch. A unique violation returns the existing id for the same organization. A database error rolls back and returns db_error without the driver message.
5. How would you test quality, security, performance, and cost?
Unit tests cover the hash, the PDF rejection, the path-like name, and the frontmatter title. Integration tests cover one-row idempotency, two organizations with the same hash, and course_mismatch. Security review checks that visibility is not read from the file and that logs omit body. Cost review checks that a retry does not insert a second body and that this handler does not call an embedder.
Hands-on Assignment
Lab note. Use a local PostgreSQL or a fake Pool that records SQL text and parameters. Do not put a production connection string in the repo. The tests in accept.test.ts need neither.
Problem. Ingest one lesson file so a retry is idempotent, a PDF is quarantined, and a frontmatter visibility key cannot publish the row.
Tasks.
Apply the migration. Confirm the unique index lists organization_id first in its column list.
Implement acceptLessonBytes, markdownTitle, and ingestLesson.
Add the unit tests from this lesson.
Show the parameter list for the insert. Identify which values are constants in SQL and which are bound, and why source_kind is a constant.
Write the quarantine error codes and the HTTP status you will return for each.
Explain what lesson 26 is allowed to copy from the row, and what it must not read from body.
Deliverable. Migration, source with no secrets, test output, a sample of the bound parameters (hash and ids are fine, body omitted), and a note on the 23505 re-read.
Challenge. Two organizations upload the same bytes concurrently with the same session bug: the insert uses the client-supplied organization. Show the smallest test that fails under that bug and passes when the organization comes from the session and the course check.
Rubric. Conceptual accuracy and architecture 20%. Working implementation and code quality 25%. Security, privacy, and responsible AI 20%. Testing, reliability, and observability 20%. Documentation and decision rationale 15%.
Common Mistakes
Taking organization_id from the form. Symptom: organization A's lesson is searchable in organization B, and lesson 24's filter agrees because the row says B. Cause: the client was treated as the source of tenancy. Fix: session organization, plus the course ownership SELECT.
Reading visibility from frontmatter. Symptom: a staff draft becomes a published chunk after someone saves the file with a copied header. Cause: the parser was also used as an authorization engine. Fix: server-set column, strip the fence later without reading keys.
Unique hash without organization. Symptom: the second customer cannot ingest a file the first customer already has, or a lookup returns the other customer's id. Cause: a global unique index. Fix: (organization_id, content_sha256, parser_version).
Check-then-insert idempotency. Symptom: two rows under load. Cause: both transactions passed the SELECT before either inserted. Fix: the unique index and 23505.
Using the filename as a storage key. Symptom: ../ writes outside the bucket prefix, or one editor overwrites another's object. Cause: a path built by string concat. Fix: uuid key, quarantine path-like names.
Marking an empty or failed parse as parsed. Symptom: the assistant abstains on a lesson the editor believes is live, or chunks the wrong text. Cause: status was set before the title and body were validated. Fix: the check constraint that pairs parsed with a document and a null error.
Embedding inside the ingest request. Symptom: a provider timeout leaves the editor unsure whether the file saved, and a retry double-charges embeddings. Cause: two failure domains shared one HTTP call. Fix: commit the document, let lesson 26 and 27 run as follow-on jobs.
Summary
Ingestion assigns identity: organization, course, visibility, hash, and parser version, using parameterized SQL and a unique index that includes the organization. Markdown is accepted as text. Other media types are quarantined. Frontmatter cannot publish a document. The bytes are now a row lesson 26 can split without re-deciding who owns them.
Next Lesson Preview
Chunking Strategies and Metadata Design splits body into retrievable passages and copies ACL fields from the document row. The way you cut the text decides whether a negation survives into the prompt lesson 24 packs.