Part 2: PHI in Foundry using open source models - Markings, Identities and Enforcing the PHI gate

Nov 17, 2026

Ronit Virwani

21 min read

Part 1 is the prerequisite. It built a gate that strips identifiers and restores verified quotes. This part assumes you have one and asks a different question: what stops anyone from going around it.

Our example is clinical. The mechanics are not. Markings, service identities and Automations work the same way for any data you can't let an identity read.

The question we couldn't answer

Everything in part 1 ran inside one function, under the user's identity.

That function could read patient records. It could also call Jev. Our checks controlled how our code used those two abilities, but the permissions allowed both.

"What stops a future function from skipping this?" the security lead asked.

Code review, we said. Neither of us liked it.

Here's the difference we were chasing:

Before: code attempts to remove PHI before the model call. After: the identity that executes the model call cannot read PHI, and the platform enforces that underneath the code.

The first is a promise. The second is a permission. This part is the walk from one to the other, with the wrong turns left in.

The shape of the answer

Before the details, the picture. Everything below is a box on it.

part2_architecture.png

Identifiable data and model-safe data travel through different security boundaries. The middle stage is the only one that talks to a model. It can read C and write F. It cannot read A, it cannot read the map that turns C back into A, and it cannot read H.

The two coloured labels are Foundry Markings. The three verbs are actions. The identities are service users. Everything else is plumbing, and the plumbing is where the mistakes were.

Mistake 1: we thought a locked project was a boundary

Our first instinct was the one everyone has. Put the raw data in one project, the de-identified data in another, give the model identity access to the second only.

Folders and roles.

It even works, right up until someone with Owner on both projects shares a dataset. Or builds a transform from the raw notes into the "safe" project. Or adds the model identity to a group that happens to have Viewer on the raw one. Nothing in a role stops any of that, because roles are designed to grant.

Foundry has two kinds of access control, and the difference is the whole point of this part.

Roles (Viewer, Editor, Owner) are discretionary. They expand access. Someone shares a folder, someone gets added to a project, and now they can read what's in it.

Markings are mandatory. They restrict. A marking is a label on a resource, and the rule is all-or-nothing: whatever your role, you cannot read a marked resource unless you are a member of every marking on it. And they propagate: a dataset built from a marked input inherits the marking. Build anything from marked data and the output is marked too, until someone with the Expand Access permission on that specific marking removes it. An Owner can't. A project admin can't. Only the marking's own administrators can, and it's logged.

That last property is what we wanted. The boundary stops being a line in a design doc that the next engineer might not read. It becomes a property of the data that follows it everywhere, and the only way across is a deliberate, permissioned, audited act.

Once we understood that, the rest of the design was two questions: what do we mark, and who is a member.

Two markings, one category

We created one marking category, scoped to our organisation, with two values. Conjunctive, so each marking is required on its own. Hidden, so people who can't see a marked resource don't learn it exists. Administered by a couple of named admins, not by project owners.

PHI_IDENTIFIABLE is for anything identifiable or directly re-linkable. The raw patient, note and inquiry datasets. The attachment store. The Deidentification Map (alias to real id, plus span offsets: the bridge back). The final reviewer ledger and the determination outputs, because restored quotes live there.

CLINICAL_DEIDENTIFIED is for text that has passed the gate and may be used by approved model workflows. The Deidentified Run, the Deidentified Sources, the Tokenized Model Results.

Why two and not one? Because de-identified is not public. A note with the patient removed still says someone had eyelid surgery and failed conservative treatment. We wanted the de-identified lane to be a closed lane too, readable by the model identity, the finalizer and a small group of humans, and nobody else.

One detail that costs an afternoon if you don't know it. Ontology object types backed by user edits don't carry markings directly. Each one has a permission dataset behind it, and the marking goes on that dataset. Mark the wrong thing and the object type looks unprotected while the table underneath is locked, or the reverse. Check both, as the identity you're worried about.

Membership of both markings goes through one small group. The group holds marking membership, not marking administration. Being able to read PHI and being able to declassify it are different powers, and we kept them in different hands.

part2_markings.png

One function crosses the line

The sentence that matters most in the whole design: the only place data crosses from PHI_IDENTIFIABLE to CLINICAL_DEIDENTIFIED is the Prepare function.

It runs as a PHI-authorised person, inside the action the hospital's screen already calls. It is the gate from part 1 with one new switch: stop before the model, hand back the redacted sources and the span maps instead of calling anything. It writes the Run and Sources under the de-identified marking and the Map under the PHI marking, in one transaction.

Nothing else writes to the de-identified objects from raw data. If someone later builds a transform from the raw notes into the de-identified project, propagation marks the output PHI_IDENTIFIABLE and the model identity loses access to it. That's not a bug we'd have to catch in review. It's the marking doing its job.

Compliance sees this as what it is: a classification boundary with one named crossing point. That's a much easier thing to approve than "trust our regexes".

The lesson: a role grants; a marking restricts. If the boundary has to hold against the next engineer's mistake, it has to be a marking, and the only crossing has to be one function you can name.

Mistake 2: we designed around a feature that was in beta

Markings say what an identity can read. Actions say what it can do. We needed a middle identity that could do the model work and read nothing marked PHI.

The first idea was Foundry's action read-authorisation feature, where an action runs with elevated read rights on behalf of the submitter. It looked like exactly the thing. We sketched the whole design around it.

Then we asked Support. It's in beta, not ready for production use, no date.

part2_read_write_auth.png

So we used the older mechanism: third-party applications with service users, each owning an Automation. Two backend applications, each with client credentials and application permissions.

Model RunnerPHI Finalizer
Member of CLINICAL_DEIDENTIFIEDyesyes
Member of PHI_IDENTIFIABLEnoyes
May submitthe Evaluate actionthe Finalize action
Ownsthe Evaluate Automationthe Finalize Automation
Can reach Jev's egress sourceyesno
Can readRun, Sources, public policy textraw sources, the Map, Tokenized Results
Can writeTokenized Model Resultsreviewer ledger, determination output, MAC review rows

Each action's submission criteria allow exactly one submitter: its own service user. Nobody else can trigger Evaluate, not even an admin, and the Model Runner can't trigger Finalize. The client secrets live in the application registry and nowhere else. Not in code, not in git, not in a dataset, not in a Workshop variable.

Then we tested it like a sceptic

The Model Runner had Viewer through the project and Owner as a default role, because that's how the sandbox was set up.

Good. That's the worst case.

Logged in as it, we opened Check access on every raw dataset, the Map, the reviewer ledger and the determination output.

Organization:        passed
Role:                passed
PHI_IDENTIFIABLE:    failed
Access:              denied

part2_access_denied.png

All denied. The three de-identified object types: CLINICAL_DEIDENTIFIED: passed, allowed.

part2_access_allowed.png

The mandatory marking beat the project role every time. That's exactly what the docs promise, and exactly what you want to see with your own eyes, as that identity, before you rely on it. Take the screenshot. It's the one the security lead will ask for.

The lesson: ask Support about the elegant feature before you design around it. Then verify the older one as the identity you're worried about, with the broadest role you can give it, and keep the evidence.

Why the work had to split into objects

Separate actions can't share memory.

That one sentence drove the whole shape. In part 1 the gate held the token map in a local variable, called the model, restored the quotes, returned. One function, one identity. To give the model stage a different identity, the work has to cross an action boundary, and the only thing that crosses an action boundary in Foundry is an ontology edit.

So the state between stages lives in four objects:

ObjectMarkingWhat it holdsWho writes it
Deidentified RunCLINICAL_DEIDENTIFIEDrandom run id, target (PA or MAC), status, engine, checklist context, countsPrepare; Evaluate and Finalize update status
Deidentified SourceCLINICAL_DEIDENTIFIEDalias (NOTE_1), kind, generic title, relative service date, redacted textPrepare
Deidentification MapPHI_IDENTIFIABLErun id, inquiry id, alias to original source id, span offsetsPrepare
Tokenized Model ResultCLINICAL_DEIDENTIFIEDrun id, requirement id, status, source alias, redacted quote, tokenized rationaleEvaluate

Three decisions in that table took us a while.

The run id is random. Not the inquiry id, not a hash of it. The Model Runner sees run ids and aliases and nothing that joins back to a patient, even for someone who also holds a list of inquiry ids.

The Map is the bridge and it holds no text. Part 1 promised the token map never left memory. That promise changed, on purpose. The Map persists alias, original source id and span offsets, and nothing else. No original text, no matched values. Finalize has to reload the original source and apply the offsets to restore a quote. That trade is what makes the identity split possible, and the restore rules didn't move: exact and unique, or NOT_EVALUATED.

The MAC case id lives in the protected context, not the safe one. The Run carries a target field the model stage can see, because "PA or MAC" isn't identifying. The case id, which is, sits in a Map row of kind RUN_CONTEXT, readable only by the Finalizer. Same object, same marking, no new permission to reason about.

The three actions

Prepare runs as the PHI-authorised person, inside the existing action. It loads the inquiry and patient, runs the deterministic triage, extracts note and PDF text, marks earlier unfinished runs for the same target SUPERSEDED, runs the gate, validates the handoff the same way it would validate an outbound request, and writes the Sources, the Map and the Run with status PASSED in one transaction. Then it returns AWAITING_RESEARCH, the status the hospital's screen already knew how to wait on.

If redaction fails for a source, that source is blocked, the affected requirements are recorded as not evaluable, and no model call will ever happen for them.

Evaluate runs as the Model Runner, from an Automation. It takes the run id, returns no edits if the run is already past this stage, loads only the Run, its Sources and the public checklist text, builds the request, runs the sealed-request check from part 1 one more time, calls Gemini or Jev, and writes one Tokenized Result per requirement with a deterministic id (runId|requirementId). Then MODEL_COMPLETE.

The identity can't read PHI, so the second check is belt and braces. It's also free, and a bug in Prepare should be caught twice, not once.

Finalize runs as the PHI Finalizer, from the second Automation. It returns no edits if the run is already FINALIZED, reads the Tokenized Results, the Map and the protected context, resolves every alias to its real source, reloads the original text, restores only exact and unique quotes, and writes the ledger. Then it branches on target: for PA, the determination output and runCompletedAt; for MAC, the case's review rows and P7 columns. Then FINALIZED.

It never sends a model request. It has no egress source and no reason to.

Mistake 3: we thought writing needed a role

Every one of the next four failed with the code perfectly fine.

Write authorisation for a function-backed action comes from the action, not from a role. The action's configuration lists the object types the function may edit, and that's the whole permission.

When we extended Finalize to write the MAC case's ledger, the function's return type grew by two object types. The action's "affected types" had to grow to match. Until it did, the edits failed at runtime with a message about an unlisted type, and the code hadn't changed.

No Editor role was ever needed, on anything.

The lesson: if you find yourself granting Editor to a service user, stop. The action configuration is probably what's missing.

Mistake 4: we forgot that reading still needs a role

The Finalizer's markings passed. Its organisation check passed. It still couldn't update the determination output.

It had no role at all on the project holding that object type. It couldn't see the thing it was allowed to edit.

Viewer fixed it. Viewer, not Editor.

The mental model that finally stuck: a marking decides whether you may see it at all; a role decides whether you can find it; an action decides whether you can change it. All three have to say yes.

The lesson: a service user needs Viewer on every project whose objects it touches, and nothing more.

Mistake 5: the egress source failed before our code ran

The Evaluate function declares Jev's egress source. Foundry resolves that declaration before the function starts, even on runs that use Gemini and never touch the source.

The Model Runner had no role on the project containing the source. Evaluate failed before a line of our code executed, with an error that pointed at nothing in the function.

It got Viewer on that project. That's wider than we'd like; the markings still deny it every raw dataset in there, but least privilege says the source should sit in a dedicated integration project with nothing else. It's on the list.

The lesson: a declared source is resolved at startup, for every path, by the submitting identity. Scope the project it lives in before you scope anything else.

Mistake 6: we passed the object instead of its id

The actions originally took the Run object as a parameter. On a global branch, the action couldn't resolve the new object type's primary key and failed on submit.

A string input for the run id sidesteps the branch problem. It also keeps the action's interface free of anything that hints at a patient: the Automation hands over an opaque string and nothing else.

The lesson: give the handoff actions the least they can work with. An opaque id is enough.

Markings are not an outbound filter

Not a mistake, but a sentence our FDE said early and we kept repeating.

Once function code has read a value, no marking inspects the JSON it sends. Markings decide who can read. The code gate decides what leaves. The identity split decides who can even try.

You need all three. Drop any one and the other two are covering for it.

The queue is an Automation, and two ways it didn't fire

An Automation watches a set of objects and, when a condition holds, submits an action as the Automation's owner. That last clause is why it's the right tool. The owner is the service user, so the action runs as the service user. That's the identity split in one setting.

Two configurations look right and aren't.

Live monitoring on "objects added" failed outright on our edit-backed Run object, with Catalog:BranchesNotFound. Live monitoring wants a dataset-backed object type with a branch to watch. An object type that exists only through user edits doesn't have one.

Scheduled monitoring on "objects added" ran, and did nothing. A scheduled "objects added" takes a baseline on its first run and fires only for objects added after it. Every run already sitting at PASSED when the Automation was created was invisible to it forever.

What works: scheduled, every minute, run on all objects where status = PASSED, with "always trigger effects when schedule is met" on. Each action changes the status, which removes its object from the eligible set. That's the whole queue. No queue service, no cron job, no cursor. Finalize is the same thing on status = MODEL_COMPLETE.

Two operational notes. Automations have an expiry date; ours expire in December and need a renewal owner before anyone relies on them. And a run sits for up to a minute between stages. The hospital's screen was already polling, so it didn't notice. The MAC panel wasn't, and it did.

The lifecycle, and why every failure ends somewhere reviewable

The run's status is the only state that matters.

part2_run_lifecycle.png

Walk the failures.

Redaction fails: no model request, Finalize writes explicit NOT_EVALUATED rows, the screen completes, and a human sees which items the machine couldn't look at.

The model errors inside the function: MODEL_FAILED, same path. Reviewable, not stuck.

The platform kills the function at its time limit: nothing commits, because ontology edits are atomic per action. The run stays PASSED and the Automation retries next minute. This happened three times in a row with Gemini, below.

Finalize's transaction fails: the run stays MODEL_COMPLETE, retry.

A user reruns: Prepare marks every unfinished run for the same target SUPERSEDED before staging a new one. A superseded run's Evaluate is a no-op and its results are never finalized. Finalized runs are never superseded. They're history.

Two properties make those retries safe. Evaluate and Finalize are idempotent: no edits if the run is already past their stage. And result ids are deterministic per run and requirement, so a retry overwrites its own rows. Without those two, "the Automation retries" would mean "the Automation duplicates".

One more thing worth saying plainly: the hospital's screen never changed. It was already written to call Run Determination, receive AWAITING_RESEARCH, and poll until runCompletedAt appeared. Prepare returns the same status. Finalize writes the same marker. No widget change, no release coordination. If you're retrofitting this, find the completion marker your UI already trusts and make the last stage write it.

Gemini vs Jev, on the same six requirements

The first controlled run in Main, through MedKong's existing action. An eyelid-surgery case, 29 checklist requirements, 6 of them needing a model.

Same answers, 21× faster. One synthetic case, not a benchmark.

part2_gemini_vs_jev.png

The three Gemini timeouts weren't failures in the usual sense. The action transaction never committed, so the run stayed PASSED and the Automation tried again until one attempt fit under the limit. A function-time budget is a design constraint, not a footnote, and a queue built on "retry until it commits" turns a hard failure into a delay.

Jev asks constrained questions (one of the approved statuses, one evidence sentence from the supplied material) instead of generating JSON, and escalates to a full-corpus pass when its own status probability drops below 0.70.

The sentinel check is exactly what it sounds like. Scan every de-identified Source and every Tokenized Result for the patient's first name, last name, member ID, DOB and inquiry id. Zero matches. Original PHI turned up in exactly one place: the reviewer ledger, where the Finalizer put it back on purpose.

Say it that way in your own write-up. "Controlled testing found zero matches for the planted identifiers in model-facing objects" is a sentence you can defend. "No PHI can ever reach the model" is not.

The MAC side rides the same run

MedKong has two reviewers: the hospital deciding whether to submit, and a reviewer playing the Medicare contractor's part (the MAC), working a seven-step panel where step P7 is the documentation review.

P7 used to call the model in-process, under the reviewer's identity. That's exactly the shape part 1 ended by calling a promise. So it moved onto the same run.

part2_shared_run.png

Advise MAC Steps still runs P1 to P6 synchronously. For P7 it prepares a run tagged MAC, puts the case id in the protected context, writes P7 as STAGED_PENDING, and returns. Evaluate can't tell a hospital run from a MAC run and doesn't need to. Finalize alone reads the target and picks the destination: the case's own rows and columns, never the hospital's determination. A rerun supersedes only that case's earlier runs, never the hospital's run on the same inquiry, never another case's.

That target-neutral middle is the property we wanted. A third caller later means one more branch in Finalize, not a second model lane and a second identity.

Three guards we tested in Main rather than assumed, and the gap one of them found.

Reviewer lock. The model is advisory; a human's ruling wins. We overrode P7 by hand while the run was still with the model. Finalize completed and the reviewer's ruling stayed exactly as written. It also exposed a gap: the case keeps a snapshot of the machine's answers, shown beside the reviewer's ruling in the audit view, and because the finalizer skipped everything when it saw the override, that snapshot still said pending. The machine's answer had nowhere to land. Fixed: the snapshot always gets the machine's result; the columns stay the reviewer's. A reviewer's authority over the decision and the record of what the machine said are two different things, and the first must never erase the second.

Decided case. Advise on a case whose record is final is refused before Prepare runs. No run, no edits.

Rapid rerun. Two Advise calls a second apart: the first run SUPERSEDED, the second finalized, one set of rows in the ledger.

The one we haven't fixed: the MAC panel doesn't poll, so P7 fills in a minute or two after the click and the reviewer refreshes. A poll on STAGED_PENDING is next.

What the auditor actually gets

The evidence for "no PHI reached Jev" is no longer a code review. It's four things anyone can check in the platform.

  1. The execution history of every Evaluate run shows the Model Runner as the identity.
  2. The Model Runner is a member of CLINICAL_DEIDENTIFIED only. Open Check access as it on any PHI_IDENTIFIABLE resource and it's denied.
  3. Every Run, Source and Result it read or wrote carries the de-identified marking, and a sentinel scan of them for the patient's identifiers finds zero matches.
  4. Original PHI reappears in exactly one place, the reviewer ledger under PHI_IDENTIFIABLE, written by the Finalizer, which is the only identity that could have.

That's a chain a security lead can sign, and none of it depends on believing us about our regexes. The gate from part 1 is still there, still tested, still the thing that decides what a request contains. What changed is that if it ever fails, the identity holding the request had nothing worse to send.

What's still open

The boundary works. A few things around it aren't finished.

Before any real patient note goes to Jev, three approvals have to land: the crossing point between the two markings, the day-count dates from Part 1, and the processing agreement with the model provider. The architecture is done. The signatures aren't.

Everything in this post ran on synthetic and demo data: 747 tests across 40 files, the controlled runs in Main, the sentinel scans, the access checks. Real charts under proper access come after the signatures, not before.

We built all this the long way on purpose, to see where it breaks before packaging it. It's about to become the next version of the sensitive data scrub and rehydrate module in the AKOS Arsenal.

What am I missing?

If you've put a model behind a marking-isolated service identity, or fought Automations on edit-backed objects, and hit something that isn't in the checklist, write me. Same if you've found a cleaner way to scope an egress source than a project role, or you got action read-authorisation working and it held.

If you're looking at a design doc that says "the function strips PHI before the call" and a security lead who isn't smiling, talk to us. We've had that meeting.

Written by

Ronit Virwani

Ronit Virwani

AI Engineer

LinkedIn

Contact us

Ready to revolutionize your Industry or Organization?

Fill out the form with as much detail as possible. The more information you provide, the better we can tailor our questions and solutions to fit your unique needs. Let's take the first step towards creating something extraordinary together.

By submitting this form, you are agreeing to the privacy policy.